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

我创建了这样的数组["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); } }); }); 

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

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

 var stuff ={'key1':'value1','key2':'value2'}; 

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

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

AJAX电话:

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

您可以将传递给result.php的数据处理为:

 $data = $_POST["result"]; $data = json_decode("$data", true); //just echo an item in the array echo "key1 : ".$data["key1"]; 

2.直接传递对象:

AJAX电话:

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

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

 //just echo an item in the array echo "key1 : ".$_POST["key1"]; 

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

如果你想发送键值对,这就是我所看到的,最好使用一个PHP JSON库(就像这个… http://php.net/manual/en/book.json.php

然后你可以发送实际的键值对,使用JSON格式,如… {“ques_5”:“19”,“ques_4”:“19”}

试试这个

 var array = ["9", "ques_5", "19", "ques_4"]; console.log(array.join(",")); 

上面的代码将输出字符串,用逗号分隔,如9,ques_5,19,ques_4然后将其粘贴到ajax调用。

然后在php explode那个字符串。

其他可能的方案。

第一

 var obj = { 'item1': 'value1', 'item2': 'value2' }; $.ajax( { type: 'post', cache: false , url: 'test/result.php', data: { result : JSON.stringify(obj) }, success: function(resp) { alert(resp); } }); 

第二

 var a = $.JSON.encode(obj); $.ajax( { type: 'post', cache: false , url: 'test/result.php', data: { result : a }, success: function(resp) { alert(resp); } }); In PHP File  

您可以将array in json格式的array in json发送到php,然后使用json_decode函数返回数组

在ajax调用中你必须发送json,你需要首先创建值的数组,以便你以正确的forms得到它,这样你的json看起来像{"ques_5":"9","ques_4":19}

并在ajax调用中使用

  data: JSON.stringify(`your created json`), contentType: "application/json; charset=utf-8", dataType: "json", 

在PHP中它看起来像

  

我想分享一个适合我的完整示例,以避免为每个php函数创建每个javascript函数

//在HTML端,通过链接进行简单的javascript调用

  test 
php function response here!

//在javascript端

  function CargaZona(fc, div, params) { var destino = "#" + div; var request = $.ajax({ url : "inc/phpfunc.php", type : "POST", data : { fc : fc, params : JSON.stringify(params) }, dataType : "html" }); request.done(function (msg) { $(destino).html(msg); }); request.fail(function (jqXHR, textStatus) { alert("Request failed: " + textStatus); }); } 

//在phpfunc.php页面上