如何使用ajax获得php响应
在html网页中,我希望PHP响应显示在如何使用ajax获得php响应,php,html,ajax,Php,Html,Ajax,在html网页中,我希望PHP响应显示在。中。 谁能告诉我怎么做,或者其他代码有什么问题吗? 谢谢~~^^ 网络代码: <html> <head> <script type="text/javascript"> $("#submit").click(function(){ $.ajax({ type: 'get', url: 'php/tes
。
中。
谁能告诉我怎么做,或者其他代码有什么问题吗?
谢谢~~^^
网络代码:
<html>
<head>
<script type="text/javascript">
$("#submit").click(function(){
$.ajax({
type: 'get',
url: 'php/test.php',
dataType:'json',
success: function(data) {
//dosomething.....
},
});
});
</script>
</head>
<body>
<form method="post">
<input id="submit" type="button" value="next">
</form>
<br><br><span id ="status"></span>
</body>
</html>
$(“#提交”)。单击(函数(){
$.ajax({
键入:“get”,
url:'php/test.php',
数据类型:'json',
成功:函数(数据){
//dosomething。。。。。
},
});
});
php代码:
<?php
echo ("success");
?>
收到响应后,执行以下操作
$("#submit").click(function(){
$.ajax({
type: 'get',
url: 'php/test.php',
dataType:'json',
success: function(data) {
$("span#status").html(data);
},
});
});
这不起作用,因为提供的数据类型不是JSON。。。jQuery中的dataType属性必须与使用PHP发送的数据类型匹配 要使用简单的“成功”消息使其正常工作,您可以执行以下操作:
$("#submit").click(function(){
$.ajax({
type: 'get',
url: 'php/test.php',
dataType:'html',
success: function(data) {
$("span#status").html(data);
},
});
});
因为您使用的是
数据类型:“json”
,所以AJAX函数认为它得到的是一个json数组。但是,由于在php中只使用“succes”进行响应,因此它不会解析为JSON
您应该使用json\u encode()
在PHP中对输出进行JSONify,然后可以在ajax中调用succes
回调,或者使用.done
函数
$("#submit").click(function(){
$.ajax({
type: 'get',
url: 'php/test.php',
dataType:'json',
success: function(data) {
$("span#status").html(data);
}
});
});
或使用.done功能:
$("#submit").click(function(){
$.ajax({
type: 'get',
url: 'php/test.php',
dataType:'json',
}).done(function(data) {
$("span#status").html(data);
});
});
在我看来,.done函数的可读性和可维护性更好。请用两个文件编辑您的问题,一个是请求php页面的文件,另一个是发送响应的文件。您希望使用json,但打印文本。将数据类型更改为文本或在php中使用json_编码