[英]JQuery AJAX call to php function
我试图用AJAX调用替换网页中的页面重载PHP脚本。
我正在使用JQuery运行AJAX脚本,但是它似乎没有做任何事情,因此我试图编写一个难以置信的基本脚本来对其进行测试。
我的目录如下
public_html/index.php
/scripts/phpfunctions.php
/jqueryfunctions.js
index.php包含
<!DOCTYPE html>
<html>
<head>
<!-- jquery functions -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="scripts/jqueryfunctions.js"></script>
<!-- php functions -->
<?php include 'scripts/phpfunctions.php' ?>
</head>
<body>
<button type="button" id="testButt">TEST</button>
</body>
</html>
然后,如果设置了参数,我尝试调用的phpfunctions.php
页面仅包含回显
<?php
if(isset($_GET["action"])) {
echo "test has been run";
}
?>
我正在尝试运行的jqueryfunctions.js
脚本是
$(document).read(function () {
$('#testButt').on('click', function () {
console.log("jquery call worked"); // this bit does run when button is clicked
$.ajax({ // this bit doesn't seem to do anything
url: 'scripts/phpfunctions.php?action=run_test',
type: 'GET',
success: function (data) {
$('#ajaxdata').html(data);
},
error: function (log) {
console.log(log.message);
}
});
});
});
我看到第一个console.log正在调用jqueryfunctions.js函数,但似乎没有在调用我的phpfunctions.php函数。
我期望看到php回显“测试已运行”,但是不会发生。
我错过了什么?
您应该使用isset()
方法:
<?php
if(isset($_GET["action"])) {
if($_GET["action"] == "run_test") {
echo "test has been run";
}
}
?>
如果您使用的是Ajax,那么为什么需要在索引页面上包含它:
<?php include 'scripts/phpfunctions.php' ?>
而且我在您的索引页面上找不到此元素$('#ajaxdata')
。
您也可以检查检查器工具的“网络”选项卡,以查看对phpfunctions.php
的xhr请求,看看是否成功或有任何错误。
我认为问题出在这里:
$(document).read(function() {
$('#testButt').on('click', function() {
console.log("jquery call worked"); // this bit does run when button is clicked
$.ajax({ // this bit doesn't seem to do anything
url: 'scripts/phpfunctions.php',
type: 'GET',
data: {action:'run_test'}, // <------ Here
success: function(data) {
$('#ajaxdata').html(data);
},
error: function(log) {
console.log(log.message);
}
});
});
});
jQuery说 :
数据要发送到服务器。 如果还不是字符串,则将其转换为查询字符串。 它被附加到GET请求的URL上。 请参阅processData选项以防止这种自动处理。 对象必须是键/值对。 如果value是一个Array,则jQuery根据传统设置的值使用相同的键序列化多个值。
因此,您应该设置data: {key:'value'}
大多数情况看起来都不错,但是您的data
属性是为“ POST”请求设计的,请尝试将数据添加到url中,如下所示:
$( document ).read( function ()
{
$( '#testButt' ).on( 'click', function ()
{
console.log( "jquery call worked" ); // this bit does run when button is clicked
$.ajax( { // this bit doesn't seem to do anything
url: 'scripts/phpfunctions.php?action=run_test', // Add the GET request to the end of the URL
type: 'GET',
//data: 'action=run_test', Unrequired noise :P (this is for post requests...)
success: function ( data )
{
$( '#ajaxdata' ).html( data );
},
error: function ( log )
{
console.log( log.message );
}
} );
} );
} );
而且( 如我的评论中所述 ),您还需要完成身体的结束标记:
</body> <!-- Add the closing > in :P -->
</html>
我希望这有帮助 :)
您在哪里加载ajaxfunctions.js? 看起来在您的代码中,您永远不会加载资源并进行更改
<button id="xxx">
在
<button type="button" id="xxx">
因此该页面不会被重新加载
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.