嗨,我似乎无法让这篇文章发挥作用。首先,我使用Typescript创建了一个类:
class ParticipantInfo {
constructor (public fname: string,
public mname: string,
public lname: string,
public ssn: string,
public sin: string,
public tin: string,
public addr1: string,
public addr2: string,
public addr3: string,
public city: string,
public state: string,
public zip: string,
public email: string,
public phone: string,
public local: string){}
}
创建了这个javascript:
var ParticipantInfo = (function () {
function ParticipantInfo(fname, mname, lname, ssn, sin, tin, addr1, addr2, addr3, city, state, zip, email, phone, local) {
this.fname = fname;
this.mname = mname;
this.lname = lname;
this.ssn = ssn;
this.sin = sin;
this.tin = tin;
this.addr1 = addr1;
this.addr2 = addr2;
this.addr3 = addr3;
this.city = city;
this.state = state;
this.zip = zip;
this.email = email;
this.phone = phone;
this.local = local;
}
return ParticipantInfo;
}());
我使用jQuery来处理我附加到表单元素的HTML按钮上的提交事件:
$(document).ready(function(){
$("#frmInquiryForm").submit(function(event){
event.preventDefault();
var formData = new ParticipantInfo($('[name="f1_fname"]').val(),
$('[name="f1_mname"]').val(),
$('[name="f1_lname"]').val(),
$('[name="f1_ssn"]').val(),
$('[name="f1_sin"]').val(),
$('[name="f1_tin"]').val(),
$('[name="f1_addr1"]').val(),
$('[name="f1_addr2"]').val(),
$('[name="f1_addr3"]').val(),
$('[name="f1_city"]').val(),
$('[name="f1_state"]').val(),
$('[name="f1_zip"]').val(),
$('[name="f1_email"]').val(),
$('[name="f1_phone"]').val(),
$('[name="f1_local"]').val());
$.ajax({
type: "POST",
url:"processForm.php",
data: JSON.stringify(formData),
success: function(data){
alert(data);
window.location = 'confirmForm.php?message='+data;
},
error: function(xhr, ajaxOptions, thrownError){
alert('status='+ajaxOptions);
alert("XHR STATUS="+xhr.status+" "+ thrownError);
}
});
})
})
仅仅是为了测试,我在processForm.php页面上所做的就是:
<?php
var_dump($_POST);
?>
来自成功的AJAX调用的警报消息仅返回&#34; array(0){}&#34;。是JSON.stringify的问题还是有其他人知道的东西?在此先感谢您的帮助!
答案 0 :(得分:0)
在发送数据之前删除JSON.stringify
。
您未在contentType
来电中指定$.ajax
,文档称默认为application/x-www-form-urlencoded
。如果你将一个对象传递给它,jquery会将你的数据编码为foo=bar&this=that
,但是你在这里传递一个编码的json字符串,从而导致意外的行为,对我而言,可能就是php收到类似"{"foo":"bar"}"
的内容虽然php只能自动解析urlencoded
请求体(因为json格式化的体在标准中相对较新)。
因此,如果您想使用application/json
content-type
,请确保在$.ajax
的选项中指定它,并在PHP中解析它$requestArray = json_decode(file_get_contents('php://input'));
。请阅读另一个问题here。