我有一个ajax问题。
我想从php中的ajax调用返回一个数组,然后从该数组中获取返回的值,以与jQuery ajax调用一起使用,但是我不知道该怎么做。谁能为我指出正确方向?
我知道ajax响应有很多不同的编码类型(我想到了json和xml),但是我真的不知道有什么用。现在,我要做的只是回显作为响应的内容,以便在页面上显示,而且我想更改当前的实现,以使用数组作为响应,而不仅仅是简单的文本。但我不知道从哪里开始阅读有关如何执行此操作的教程。
此外,如果我可以回显文本并得到想要的内容,那么使用编码类型有什么意义呢? 如果可以回显以显示,我想我真就用不到json类型或xml了。
Well, to start off encoding types are there specifically to solve a problem such as the one you posed. They are there to organize multiple bits of information in a response, so you can return an array, or list, or multiple rows from a database, etc.
Json is my personal favorite, because of how light it is on syntax. To pass the array from the PHP to javascript with AJAX, you'd first encode your array to json (basically taking the PHP array object, and making a text representation of it). You can do this using PHP's json_encode()
function (PHP.NET reference).
Next you'll need to fetch that somehow, I will recommend Jquery here, because of their built in functions. Using Jquery, you would type something like:
$.ajax({
url: "ajax.php",
data: {"somedata":"somedata"},
success: function (data)
{
alert(data);
},
dataType: "json" /*now jquery will parse the json for you*/
});
In this code the anonymous function in the success will be called when the Ajax has returned information. Because Jquery is great, it'll already have parsed the json, and put it in the object data. Now each array item you passed from your php will be accessible via data.[ArrayKey]
.
Also, you had asked for a tutorial, here is one that seems to be pretty good: http://www.jquery4u.com/json/ajaxjquery-getjson-simple/#.T8PGz9VYua8
Hope that helps explain it a little better, I can give you an example if you like.
If you're returning arrays, I think JSON is the best way to go.
Its actually really easy to do.
PHP:
$array=array();//this is my array
$array=json_encode($array);//encode the array to JSON format, so that jQuery can decode it.
echo $array;//print it on screen
Now use some jQuery:
$.getJSON('http://mysite.com/myphpscript.php', function(my_data){
//now, my_data is your array..
//so access it like this:
alert(my_data.keyname);//"keyname" is an array key of your array
});//end of ajax request
The point of encoding your array is so that jQuery can pick it up as an array (with the help of JSON), and not just standard text.