[英]jQuery Ajax is not getting posted to a PHP file
我是AJAX的新手所以我知道我的代碼中可能存在一個愚蠢的錯誤,但無論如何我都會繼續。
我創建了一個在單擊按鈕時調用的函數。 該函數調用jquery的.ajax()
方法。 我將數據發送到名為'delete_post.php`的文件。
HTML:
<button class="btn btn-primary" onclick="deletePost(<?php echo $_GET["id"]; ?>);">Yes</button>
上面的代碼有效。
JS:
function deletePost(postid) {
$.ajax({
type: 'post',
url: "delete_post.php?id="+postid,
success: function(data) {
if(data.error == true) console.log('error');
else console.log('problem?');
}
});
}
上面的代碼調用.ajax()
函數但是沒有記錄'問題?' 進入控制台。
這是PHP文件:
<?php
require_once '...';
if(isset($_GET["id"])) {
$id = $_GET["id"];
echo "YEAH!";
} else {
header("location: index.php");
}
?>
問題是什么,我該如何解決?
正如我們在聊天方面討論的那樣,您可以像這樣使用它:
JS:
function deletePost(postid) {
$.post('delete_post.php', {id : postid}, function(data){
console.log(data);
}, 'json');
}
PHP:
<?php
require_once '...';
if(isset($_POST["id"])) {
$data['res'] = 'yes';
echo json_encode($data);
} else {
header("location: index.php");
}
?>
以下部分有一個轉義問題:
onclick="deletePost(<?php echo $_GET["id"]; ?>);"
必須如下:
onclick="deletePost(<?php echo $_GET['id']; ?>);"
並且,你回應'YEAH!',所以if條件應該是:
if(data == 'YEAH!')
這是您的工作代碼,在您的AJAX中,您正在“POST”,在您的PHP文件中使用“GET”。
trigger.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
<script>
function deletePost(postid) {
$.ajax({
type: 'GET',
url: "http://localhost/overflow/delete_post.php?id="+postid,
success: function(data) {
console.log('success:'+data);
}, error: function(xhr, status, error){
console.log(xhr.responseText);
}
});
}
</script>
</head>
<body>
<button class="btn btn-primary" onclick="deletePost(9); return false;">Yes</button>
</body>
</html>
delete_post.php
<?php
//require_once '...';
if(isset($_GET["id"])) {
$id = $_GET["id"];
echo "YEAH!";
//do something
} else {
// header("location: index.php");
echo "not set";
}
?>
試試這個,讓我們詳細清楚地了解您的問題。 祝好運
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.