douping5226 2015-11-07 21:11
浏览 48
已采纳

在我的javascript中通过ajax接收php数据作为数组而不是responseText

Currently I have an ajax setup where my page with javascript calls a php file which then returns data via xhttp.responseText. This works great for strings but when I pass it a json encoded array, it still views that results as text. I get a string formatted version of my array that looks like this [1,2,3,4,5,6,7]

Which sort of works, but it's inconvenient because it's text representing an array and not an actual array.

How can I receive the data as an array instead of an array in text format? Currently I can still get the data using split(), but that seems sloppy. Is there an alternative to xhttp.responseText that would work better?

  • 写回答

2条回答 默认 最新

  • douxian1923 2015-11-07 21:14
    关注

    You can try sending your data as a JSON, which will give you all the flexibility in the kind of structure you want the data to have. PHP has the function json_encode which will convert your PHP variable into a JSON and you can receive this on the client side.

    1. First, make sure your PHP encodes the JSON as I said and that you have the proper header set too, i.e. header('Content-Type: application/json');

    2. Next, in your AJAX code, do JSON.parse(xhttp.responseText) to retrieve the JSON data as JavaScript object.

    3. Then you can do whatever you want with this object. Also, you can check your PHP is sending a JSON via xhttp.getResponseHeader("Content-type") which should return "application/json" if you are sending a JSON object.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办