简体   繁体   中英

Decoding json object in javascript that is returned from ajax

I've prepared an array in php for ajax return with json_encode. When returned through ajax, it is not behaving as I expected.

ajax call and my attempt to interrogate results

$.ajax({

     url:"dbpaginate.php",
              type:"POST",
              data: {'environmentvars': tmp},
    cache: false,

    success: function(response){
        alert('Returned from ajax: ' + response);
        alert(response["actionfunction"]);
        $j.each(response, function (index,element) {
            alert(index);
            alert(element);


        });
});

first alert message:

Returned from ajax: array(5) {
["actionfunction"]=>
string(8) "showData"
["sortparam"]=>
string(6) "ticker"
["sortorder"]=>
string(3) "ASC"
["page"]=>
int(1)
["htmlstring"]=>
string(0) ""
}
{"actionfunction":"showData","sortparam":"ticker","sortorder":"ASC","page":1,"htmlstring":"","htmltext":"<table id=\"summaryheader\"> [...lots of html...]<\/div>\n"}

Second alert message

undefined

Expected result

showData

How can I effectively port my json response into a javascript object environmentvars? Thanks.

You have to make the response valid JSON. It seems you have a print_r statement somewhere in your server side script, whose output gets included into the response. Remove that.

The response is always text, ie a string in JavaScript . You can parse the JSON before processing the data futher ( Parse JSON in JavaScript? ) or tell jQuery to parse it for you, by adding the dataType: 'json' option.

You should specify a dataType parameter in such methods which is basically used to declare the type of data you are expecting from the server.

Here is an example:

$.ajax({
  type: "POST",
  url: <your-request-url>,
  data: <your-data>,
  success: function(){ ... },
  dataType: "json"
});

More details here: https://api.jquery.com/jquery.post/

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