当我在JQuery代码的主体中调用Ajax时,它返回正确的结果,但是当我从函数内部调用它时,它失败。下面是服务器端代码:在函数内调用时Ajax失败
<?php
$what = $_POST["what"];
$where = $_POST["where"];
if(isset($what)){
$data = array(
"what" => $what,
"where" => $where,
);
echo json_encode($data);
}
?>
下面是成功(返回文本浏览器)的代码:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
what = "dog";
where = "in the manger";
$.ajax({
url: "test.php",
type: "POST",
data: {what : what, where : where},
dataType: "json",
success: function (data)
{
$("#result").text(JSON.stringify(data));
},
error: function (error)
{
alert("ajax error ");
}
});
</script>
</head>
<body> <div id="result"></div> </body>
</html>
,这里是代码失败(提醒“错误”): `
<html>
<head>
src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
what = "dog";
where = "in the manger";
function get_click() {
$.ajax({
url: "test.php",
type: "POST",
data: {what : what, where : where},
dataType: "json",
success: function (data)
{
$("#result1").text(JSON.stringify(data));
},
error: function (error)
{
alert("ajax error " + JSON.stringify(error));
}
});
}
</script>
</head>
<body>
<div id="result1"></div> </body>
<form onsubmit="get_click()">
<input type="submit">
</form>
</body>
</html>
我想使功能包裹的Ajax调用工作,因为我需要它发送到服务器之前处理来自表单的数据。我在做什么错误?
环境是一个无头的树莓派与Raspbian操作系统,在Windows 10
我看到几个问题开始。 1)你连接jquery两次。 2)你的jQuery链接之一是在html开头之上。 –