如何在PHP脚本中访问从jQuery.ajax()的HTML页面传递的表单数据的各个值?

我将表单数据传递给PHP脚本以通过JS( jQuery.ajax() )进行处理。

问题是 – 我无法找到一种方法来访问PHP中的单个表单控件值(例如$_POST['zipcode'] )。

相反,我只能使用$_POST['form']访问数据,这是一个表示为一个长字符串的整个表单(例如string(89)"color=red&color=blue&zipcode=12345..." )。

如何通过JS访问从HTML表单传递的PHP脚本中的表单数据的各个值?

的index.php(forms)的

  
Red Green Blue

的index.php(JS)

 $('#myform').on('submit', function(e) { e.preventDefault(); $.ajax({ type: 'POST', dataType: 'html', url : 'PHPscript.php', data: {form : $('#myform').serialize()} }).done(function(data) { var myJSONresult = data; alert(myJSONresult); }); }); 

PHPscript

  

编辑: 邮政编码字段:

 $("#zipcode").focus(function(){ if(this.value == "zipcode"){ $(this).val(""); } }).blur(function(){ if(this.value == ""){ $(this).val("zipcode"); } }); 

您需要在表单数据上使用serializeArray()而不是序列化。 这将作为一个数组提交。

 data: $('#myform').serializeArray() 

HTML

  

PHP

 if(isset($_POST["action"])) { //code } 

dataType: 'json'添加到您的ajax处理程序并进一步修改您的代码,如下所示:

 $.ajax({ type: 'POST', dataType: 'json', // changed to json url : 'PHPscript.php', data: {form : $('#myform').serialize()}, success : function(data){ // added success handler var myJSONresult = data; alert(myJSONresult.yourFieldName); } }); 

将传统设置为真如

 $.ajax({ traditional:true, //your rest of the ajax code }); 

在PHP端,你得到的价值很好,问题是在表格序列化结束