开发者

Getting array to .ajax on success

开发者 https://www.devze.com 2023-01-11 00:39 出处:网络
I\'m trying to return data as an array to my .aja开发者_如何学Gox function on success so I can do do multiple things, but I can\'t get to work for anything except a single value.Like return $foo.But w

I'm trying to return data as an array to my .aja开发者_如何学Gox function on success so I can do do multiple things, but I can't get to work for anything except a single value. Like return $foo. But when I return $array, the page never loads up.


JavaScript's use & utilizing of array is different as compared to PHP's processing. So, either you need to send the data to your AJAX function as a JSON (JavaScript Object Notation), otherwise you need to send the data as a string with a common separator to your AJAX function.

In the latter case, you will need to split up the Response Text in your AJAX function, with that common separator, to make up a JS Array. Then it will be very much easy to use that array instead.

Hope it helps.


You would have to serialize your data into a string. My preference is JSON, so if your PHP version is >= 5.2.0, you'll most likely have access to a json_encode function. This will turn the PHP object into a JSON string. If you don't have access to json_encode, you can use the PECL JSON package.

Looking at the way you reference your ".ajax" function, I am assuming jQuery. So as long as you set the content type to 'json', the JSON response will result in a native JavaScript object. For example,

PHP,

return json_encode(array(1, 2, 3));

JavaScript,

$.ajax({
    ...
    contentType: 'json',
    success: function(response) {
    for (var i = 0; i < response.length; i++) {
        alert(response[i]);
    }
});

This code should proceed to alert 1, 2, and then 3.

I haven't verified the code, but the essential parts are all there. A note to have though, a normal indexed array is turned into a JavaScript list while an associative array will be turned into a JavaScript object.


JSON is a good option to send your data array from PHP to Javascript. In PHP side just encode and return your data array as JSON string and in the Javascript side decode that JSON string and use as normal array.

Suppose your data array is like $array, in your PHP code just encode that array using json_encode($array) and return the resulted JSON string.

In your javascript code decode that JSON string using 'eval' function in the success callback function like:

$.ajax({
   type: "GET",
   url: "test.php",
   success: function(data) {
    var dataArray = eval('(' + data + ')');
  }
 });

I think this will help you ...

Siva

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号