将带有ajax请求的数组发送到php

Mah*_*man 11 javascript php ajax jquery

我创建了这样的数组["9", "ques_5", "19", "ques_4"].现在我想将它从JS发送到PHP,但我没有得到正确的结果.我的JS代码是:

$(".button").click(function(e) {

    e.preventDefault();
    $.ajax({
        type    : 'post', 
        cache   : false,
        url     : 'test/result.php',
        data    : {result : stuff},
        success: function(resp) {
            alert(resp);
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,stuff是包含记录的数组.如何使用上面的代码发送此数组,然后在PHP中我想像处理stuff密钥一样处理此数组并ques_5成为该键的值.

She*_*ose 22

您可以将数据作为JSON对象传递给PHP脚本.假设您的JSON对象如下:

var stuff ={'key1':'value1','key2':'value2'};
Run Code Online (Sandbox Code Playgroud)

您可以通过两种方式将此对象传递给php代码:

1.将对象作为字符串传递:

AJAX电话:

$.ajax({
    type    : 'POST',
    url     : 'result.php',
    data    : {result:JSON.stringify(stuff)},
    success : function(response) {
        alert(response);
    }    
});
Run Code Online (Sandbox Code Playgroud)

您可以处理传递给result.phpas 的数据:

$data    = $_POST["result"];
$data    = json_decode("$data", true);

//just echo an item in the array
echo "key1 : ".$data["key1"];
Run Code Online (Sandbox Code Playgroud)

2.直接传递对象:

AJAX电话:

$.ajax({
    type    : 'POST',
    url     : 'result.php',
    data    : stuff,
    success : function(response) {
        alert(response);
    }    
});
Run Code Online (Sandbox Code Playgroud)

直接result.php$_POST数组处理数据:

//just echo an item in the array
echo "key1 : ".$_POST["key1"];
Run Code Online (Sandbox Code Playgroud)

在这里我建议第二种方法.但你应该尝试两个:-)