1

我是 AJAX 新手,所以我知道我的代码中可能有一个愚蠢的错误,但无论如何我会继续。

我创建了一个在单击按钮时调用的函数。该函数调用.ajax()jquery的方法。我将数据发送到名为“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");
}
?>

有什么问题,我该如何解决?

4

3 回答 3

4

正如我们在聊天方面所讨论的,您可以像这样使用它:

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"); 
    } 
    ?> 
于 2013-09-29T10:56:25.960 回答
0

以下部分存在逃逸问题:

onclick="deletePost(<?php echo $_GET["id"]; ?>);"

它必须如下所示:

onclick="deletePost(<?php echo $_GET['id']; ?>);"

而且,您正在呼应“是!”,因此 if 条件应该是:

if(data == 'YEAH!')
于 2013-09-29T10:24:05.777 回答
0

这是您的工作代码,在您的 AJAX 中您正在执行“POST”,在您的 PHP 文件中您正在使用“GET”。

触发器.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";
}
?>

试试这个,让我们详细而清晰地知道您的问题。祝你好运

于 2013-09-29T10:46:55.713 回答