我使用的是另一个stackoverflow文章所使用的代码,但有一部分对我不起作用。
<script>
// variable to hold request
var request;
// bind to the submit event of our form
$("#notification").submit(function(event){
// prevent default posting of form
event.preventDefault();
// abort any pending request
if (request) {
request.abort();
}
// let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
// let's disable the inputs for the duration of the ajax request
$inputs.prop("disabled", true);
//this code was added by me cause i saw that when i pass as data {notTitle:"smth"}
//it works, so i wanted to remake that structure and include all my elements.
// Apparently it does not work, maybe because i create a string and by
//{notTitle:"smth"}, notTitle is not passed as string.
x=$("form").serializeArray();
var str="{";
var size = x.length;
$.each(x, function(i, field){
if (field.value!="")
str = str.concat(field.name + ":" + field.value);
else
str = str.concat(field.name + ":" + "k");
if(i!=size-1)
str=str.concat(",");
});
str=str.concat("}");
// fire off the request to /form.php
request = $.ajax({
url: "test.php",
type: "POST",
dataType: 'json',
data: str//{notTitle:"s",notType:''}
});
// callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
alert(response.status);
});
// callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// log the error to the console
alert(
"The following error occured: "+
textStatus, errorThrown
);
});
// callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// reenable the inputs
$inputs.prop("disabled", false);
});
});
</script>
这是我的php
<?php $result = array("status" => "1", "a" => "2");
$notificationTitle = htmlspecialchars($_POST["notTitle"],ENT_QUOTES,'ISO-8859-1');
echo json_encode($result); ?>
在您建议使用序列化表单之前,我尝试了它并且它不起作用。我注意到的是,当我尝试将数据传递给我的php文件时,我无法通过$ _POST ['name of element']读取它们。所以,如果我评论php文件的第二行并作为数据传递{notTitle:'s'}它可以工作,我看到了成功的消息。