2013-09-29 98 views
1

我是AJAX新手,所以我知道我的代码中可能存在一个愚蠢的错误,但无论如何我会继续。jQuery Ajax没有发布到PHP文件

我有一个函数,当点击一个按钮时被调用。该函数调用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"); 
} 
?> 

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

+0

你尝试登录'data'本身? –

+0

不,数据不是JSON。 –

+0

@JakubMichálek东西正在记录,但没有任何显示 –

回答

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"); 
    } 
    ?> 
0

中有以下部分的逃生问题:

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

它必须是如下:

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

而且,你是呼应“YEAH!”,所以如果条件应该是:

if(data == 'YEAH!') 
+1

不需要转义,内部''“'在PHP中,外部在HTML中。 ;) –

+0

Ofcourse这需要转义或使用单引号。整个html是一个字符串,并且onclick会在遇到匹配的双引号时突然结束 – Rajesh

+0

不,输出将是'onclick =“deletePost(6);”'例如,没有额外的引号...... –

0

这是您的工作代码,在您的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"; 
} 
?> 

试试这个,让我们知道详细和明确你的问题。好运