【发布时间】:2014-11-11 05:48:06
【问题描述】:
我正在使用 AJAX 将变量从表单传递到 PHP 页面以处理数据库中的数据。
一旦用户点击一个按钮,它就会触发以下 JavaScript:
$(document).ready(function() {
$("#myForm").submit(function(event) {
/* validate the fields */
var firstDate= "11/10/2014"
var secondDate = "10/10/2014"
var myString = "some Text";
var myArray = ["name1", "name2", "name3", "123-123-33gf"];
processIT(firstDate, secondDate, muString, myArray);
});/* end of submit */
});
function processIT(firstDate, secondDate, muString, myArray) {
var response = "";
$(function () {
$.ajax({
url: 'api.php', // the script to call to get data
type: "POST",
data: {
firstDate: firstDate,
secondDate : secondDate ,
myString : myString ,
myArray : myArray ,
}, // you can insert url argumnets here to pass to api.php
dataType: 'json', // return data format
success: function(data) { //
alert(data);
},
error: function (jqXHR, textStatus, errorThrown){
console.log(textStatus, errorThrown);
},
});
});
return response;
}
api.php页面有以下内容
<?php
if ( isset($_POST["firstDate"]) && !empty($_POST["firstDate"])){
$response .= "<p>firstDate= " . $_POST["firstDate"] . "</p>";
}
else $response .= " 1 ";
if ( isset($_POST["secondDate"]) && !empty($_POST["secondDate"])){
$response .= "<p>secondDate = " . $_POST["secondDate"] . "</p>";
}
else $response .= " 2 ";
if ( isset($_POST["myString"]) && !empty($_POST["myString"])){
$response .= "<p>myString = " . $_POST["myString"] . "</p>";
}
else $response .= " 3 ";
if ( isset($_POST["myArray"]) && !empty($_POST["myArray"])){
$response .= "<p>myArray = " . $_POST["myArray"] . "</p>";
}
else $response .= " 4 ";
echo json_encode($response);
?>
但是当我点击按钮时出现以下错误:
SyntaxError:JSON.parse:第 1 行第 1 列出现意外字符 JSON 数据
但是如果我将 POST 更改为 GET,我可以看到传递的变量,但仍然会出现相同的错误。
任何想法我做错了什么?
【问题讨论】:
-
SyntaxError: JSON.parse表示服务器返回的JSON无效。 -
ALSO...为什么你的PHP中有
console.log?!这肯定会引发错误。 -
只需在浏览器开发工具的网络面板中查看对请求的实际响应 - 很可能已经告诉您哪里搞砸了。
-
另外,您还有
$_POST["myString "]。为什么那里有空间?您的密钥是"myString",而不是"myString "。 -
请注意,您不能在
processIT函数中执行return response;。 AJAX 是异步的,这意味着它在后台运行并在准备就绪时调用其回调。您不能从 AJAX 调用中返回。另外,为什么processIT里面有$(function () {?
标签: javascript php ajax forms variables