我在这里有一个简单的表格:
10000 loops, best of 3: 23.5 µs per loop
然后我阻止默认操作发生:
<form class="form" id="loginForm">
<div class="form-group">
<label for="affiliate">Affiliate</label>
<select class="form-control" id="affiliate" name="affiliate">
{{#list locations}}{{name}}{{/list}}
</select>
</div>
<div class="form-group">
<label for="uname">Username</label>
<input type="text" class="form-control" name="uname" id="uname">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" name="password">
</div>
<button type="submit" class="btn btn-lg float-right" id="btnLogin">Login</button>
</form>
在attemptLogin方法中
$('form').submit(function(event) {
event.preventDefault();
//attempt to log in to the system
attemptLogin(event)
});
}
在PHP方面,我尝试过POST数组的print_r,echo,var dump和json_encode,但它总是空的。表单数据未发送。在发送ajax请求之前,我打印json数据以确保它确实在那里:
function attemptLogin(form){
//convert our form data to an array, then convert that array to JSON
var formData = JSON.stringify($('#loginForm').serializeArray());
//url for login, in future should be grabbed from action of form
var url = "http://www.rsbmat.com/api/login.php";
//debug statement
console.log(formData);
//make an ajax call to the server
$.ajax({
//sent header information with ajax call, so app and server know that information can be sent back
header: {'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': "Content-Type, Origin, Accept, X-Requested-With"},
//method to send data to server
method: "POST",
//url the data will be sent
url: url,
cache: false,
//data we are sending
data: formData,
//allow cross domain
crossDomain: true,
//type of content going to be sent
contentType: "application/json",
//type of data we are receiving
dataType: "json",
//this is called BEFORE the ajax call is sent
beforeSend: function(xhr){
xhr.withCredentials = true;
}
//when it's finished what do we do with data sent back
}).done(function(data){
console.log(data);
});
然而,数据存在,从服务器收到的信息仍然是空的。
[{"name":"affiliate","value":"South King County"},{"name":"uname","value":"testuser"},{"name":"password","value":"testpassword"}]
我已将所有内容注释掉,只是让POST打印..它确实回显给应用程序,我可以在console.log中看到它,但它是空的。