doudou5101 2013-02-14 18:25
浏览 50
已采纳

如何从ajax调用传递的php访问数组中的所有元素?

I am finding difficulty in accessing elements in an array from php file. The array is passed through an ajax call. Please find below the ajax call.

var data = ['test1', 'test2', 'test3'];
$(document).ready(function () {
    $("button").click(function () {
        $.ajax({
            type: "POST",
            url: "getResult.php",
            data: {
                testData: data
            },
            success: function (data, status) {
                alert("Data: " + data + "
Status: " + status);
            }
        });
        return false;
    });
});

The server side [PHP] code is

$myArray = $_POST["testData"];
echo $myArray; 

However $myArray always returns last element[test3 here] in the array. How do I access first [here test1] and other elements? Pls help.

  • 写回答

4条回答 默认 最新

  • douhuang9886 2013-02-14 18:31
    关注

    What you need to do is convert the JavaScript array to JSON and then send over that JSON. On the PHP side you should decode the JSON back into an array. Finally, you should re-encode the array as JSON before sending it back.

    On your client side change one line:

    data: {testData : JSON.stringify(data)},
    

    On your server side do:

    $myArray = json_decode($_POST["testData"]);
    header('Content-Type: application/json');
    echo json_encode(array('pheeds' => $pheeds, 'res' => $res));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败