如何使用ajax返回并处理php文件返回的数组?

时间:2022-10-08 17:24:41

I've a php file which processes a query and returns an array.

我有一个处理查询并返回数组的php文件。

How do i get these and array and parse them and display them using ajax.

我如何获取这些和数组并解析它们并使用ajax显示它们。

I call the file using ajax. Its used to display the matching products while typing a text box with the price...

我用ajax调用该文件。它用于显示匹配的产品,同时键入价格的文本框...

responseText doesn't return anything...

responseText不返回任何内容......

1 个解决方案

#1


1  

Your data needs to be encoded in a format that JavaScript can understand, like JSON. You want to serialize the PHP array and return that as the HTTP Response, more information on how to JSON serialize data can be found here. Once the data is serialized, you can parse it in the ResponseText as though it were a JavaScript object (i.e. you can pull data like this: ResponseText[0].some_key)

您的数据需要以JavaScript可以理解的格式进行编码,例如JSON。您希望序列化PHP数组并将其作为HTTP响应返回,有关如何JSON序列化数据的更多信息可以在此处找到。一旦数据被序列化,你可以在ResponseText中解析它,好像它是一个JavaScript对象(即你可以拉这样的数据:ResponseText [0] .some_key)

I should note that jQuery makes this very, VERY easy. Like... this easy:

我应该注意到jQuery非常简单。喜欢......这很容易:

var url = '/json-data.php?id=2';

$.getJSON(url, function(data) {
    $("#target").text(data.some_key);
}

#1


1  

Your data needs to be encoded in a format that JavaScript can understand, like JSON. You want to serialize the PHP array and return that as the HTTP Response, more information on how to JSON serialize data can be found here. Once the data is serialized, you can parse it in the ResponseText as though it were a JavaScript object (i.e. you can pull data like this: ResponseText[0].some_key)

您的数据需要以JavaScript可以理解的格式进行编码,例如JSON。您希望序列化PHP数组并将其作为HTTP响应返回,有关如何JSON序列化数据的更多信息可以在此处找到。一旦数据被序列化,你可以在ResponseText中解析它,好像它是一个JavaScript对象(即你可以拉这样的数据:ResponseText [0] .some_key)

I should note that jQuery makes this very, VERY easy. Like... this easy:

我应该注意到jQuery非常简单。喜欢......这很容易:

var url = '/json-data.php?id=2';

$.getJSON(url, function(data) {
    $("#target").text(data.some_key);
}