简体   繁体   中英

PHP: how to extract ajax array response

I am getting ajax response in array format from php url. How to extract array response values in jQuery? FYI:

PHP array is:

$response = array('msg' => 'Hello', 'html' => '<b>Good bye</b>');

I am getting $response array in my ajax response. ie

var promo = "promo=45fdf4684sfd";
$.ajax({
    type: "POST",
    url: baseJsUrl + "/users/calc_discount",
    data: promo,
    success: function (msg) { // I am getting $response here as ajax response.
        //alert(msg);

        // Here I want to check whether response is in array format or not. if it is in array format, I want to extract msg here and want to use response array values.
    }
});

Let me know answer pls. Thanks.

You should echo that $response with json_encode() .

You should probably set dataType: 'json' too inside the object literal you send to $.ajax() .

Then you can access it natively with JavaScript using the dot operator inside your success callback...

function(msg) {
    alert(msg.html);
}

BTW, this line...

$response = array(['msg'] => 'Hello', 'html' => '<b>Good bye</b>');

... isn't valid PHP . Remove the brackets from the first key.

我最喜欢的解决方案是使用PHP的函数json_encode()对数组进行编码,因此jquery乐于对其进行解析。

I presume that you mean a JSON response, like this:

{"msg":"Hello","html":"<b>Good bye<\/b>"}

This is actually a native JS object, so you can use it right away like this:

success: function(msg){
   alert(msg.msg);
   alert(msg.html);
}

You can also use the jQuery.each() function to loop over all properties of the JSON object if you need to:

jQuery.each(msg, function(key, val) {
  alert(key + "=" + val);
});

and If you do not have control over the PHP output then you can use another method to get the result. Another solution is using http://phpjs.org/ library. Here you can find many functions available in JS as available in php. Usage is also same as that of PHP. So I feel if you get the json_encode/json_decode from there and use that then it can solve your problem easily.

Remember you can compile your needed functions only. In your case, it is json_encode and json_decode. No need to download whole library. Url to compile your library: http://phpjs.org/packages/configure

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM