[英]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.