[英]How to access individual values of form data, passed from an HTML page with jQuery.ajax(), inside a PHP script?
I'm passing form data to a PHP script for processing via JS( jQuery.ajax()
). 我正在将表单数据传递给PHP脚本以通过JS(
jQuery.ajax()
)进行处理。
Problem is - I can't figure out a way to access individual form control values inside PHP( eg $_POST['zipcode']
). 问题是-我想不出一种方法来访问PHP内部的单个表单控件值(例如
$_POST['zipcode']
)。
Instead I can only access the data with $_POST['form']
, which is an entire form represented as one long string( eg string(89)"color=red&color=blue&zipcode=12345..."
). 取而代之的是,我只能使用
$_POST['form']
来访问数据,它是表示为一个长字符串的完整表单(例如string(89)"color=red&color=blue&zipcode=12345..."
)。
How can I access individual values of form data inside PHP script passed from a HTML form via JS? 如何通过JS从HTML表单传递的PHP脚本中访问表单数据中的表单数据的各个值?
index.php(form) 的index.php(形式)的
<form id="myform">
<select name="color" id="color">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<input type="text" id="zipcode" name="zipcode" />
<input type="submit" id="submit" name="submit" value="Submit" />
</form>
index.php(JS) 的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 PHPscript
<?php
if(isset($_POST["form"])){
$form = $_POST["form"];
$myzipcode = $_POST['zipcode']; // won't work; will be null or empty
echo json_encode($form);
}
?>
EDIT: The zipcode field: 编辑: 邮政编码字段:
$("#zipcode").focus(function(){
if(this.value == "zipcode"){
$(this).val("");
}
}).blur(function(){
if(this.value == ""){
$(this).val("zipcode");
}
});
You need to use serializeArray() on the form data instead of serialize. 您需要在表单数据上使用serializeArray()而不是序列化。 That will submit as an array.
那将作为数组提交。
data: $('#myform').serializeArray()
HTML HTML
<input type="hidden" name="action" value="submit" />
PHP PHP
if(isset($_POST["action"]))
{
//code
}
Add dataType: 'json'
to your ajax handler and further modify your code like this: 将
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);
}
});
set traditional to true like 将传统设为真像
$.ajax({
traditional:true,
//your rest of the ajax code
});
on the php end you are getting the value fine the problem is at the form serialization end 在php端,您可以得到很好的值,问题出在表单序列化端
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.