dqjo4340 2015-05-09 10:34
浏览 48
已采纳

在没有JQuery的情况下通过Ajax / JSON发送数组

I'm experimenting with Ajax and am trying to send a 1-dimensional, non associative array from a PHP function to a calling javascript function. The array is simple stuff like:

  1. $arr[0] = 1900-1905
  2. $arr[1] = 1905-1911

etc. For various reasons I'm using jQuery, but I am reasonably familiar with the raw Javascript way of using Ajax but I can't seem to find a way how to process the JSON data client side using Javascript. I'm going to be calling the PHP function using a call to something like

myserver.com/myfunction.php?var1=1&var2=2&var3=3

and I know you have to use echo json_encode($arr) in the PHP function, but what do you do in the Ajax method to convert the JSON back into an array, and access the array elements? From reading some of the answers on this forum, this is the part where people fall at the hurdle.

Many thanks.

  • 写回答

2条回答 默认 最新

  • douyi6290 2015-05-09 10:46
    关注

    Try This

    1. function callAjax()
    2. {
    3. var xmlhttp;
    4. if (window.XMLHttpRequest)
    5. {
    6. xmlhttp=new XMLHttpRequest();
    7. }
    8. else
    9. {
    10. xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    11. }
    12. xmlhttp.onreadystatechange=function()
    13. {
    14. if (xmlhttp.readyState==4 && xmlhttp.status==200) //Success
    15. {
    16. var objResponse = JSON.parse(xmlhttp.responseText); //JSON.parse Parses a string as JSON
    17. console.log(objResponse[0]); //1900-1905
    18. }
    19. }
    20. xmlhttp.open("GET","myserver.com/myfunction.php?var1=1&var2=2&var3=3",true);
    21. xmlhttp.send();
    22. }
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部