dqjo4340 2015-05-09 18: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:

$arr[0] = 1900-1905
$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 18:46
    关注

    Try This

    function callAjax()
    {
    var xmlhttp;
    if (window.XMLHttpRequest)
      {
      xmlhttp=new XMLHttpRequest();
      }
    else
      {
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    xmlhttp.onreadystatechange=function()
      {
      if (xmlhttp.readyState==4 && xmlhttp.status==200) //Success
        {
            var objResponse = JSON.parse(xmlhttp.responseText); //JSON.parse Parses a string as JSON
            console.log(objResponse[0]); //1900-1905
        }
      }
    xmlhttp.open("GET","myserver.com/myfunction.php?var1=1&var2=2&var3=3",true);
    xmlhttp.send();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法