为什么ajax不能与POST方法一起工作


Why ajax doesn't work with POST method?

我有一个按钮与onclick="sendNews()"和PHP脚本做数据库工作。问题是sendNews运行时,$_POST数组为空

Javascript:

function sendNews()
{
    var title=document.getElementById("title").innerHTML;
    var body=document.getElementById("boddy").innerHTML;
    var params="title="+title+"&body="+body;
    var xmlhttp;
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    //Send the proper header information along with the request    
    xmlhttp.open("POST","sendnews.php",true);
    xmlhttp.send(params);
    xmlhttp.onreadystatechange=function(){
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            document.getElementById("newsAddResult").innerHTML=xmlhttp.responseText;
        }     
    }
}
PHP:

<?php
include("../inc/functions.php");
if(!loginCheck())
    header('Location: index.php');
$title=@$_POST['title'];
$body=@$_POST['body'];
var_dump($_POST);
$q=sprintf("insert into `news`(`id`,`title`,`body`,`time`) values(NULL,'%s','%s','%s')",$title,$body,jgmdate('l jS F Y h:i:s A'));
mysql_query($q) or die("خطا".mysql_error());
echo "با موفقیت ارسال شد";
?>

有什么问题吗?

我明白了…要使用ajax发送POST请求,需要在xmlhttp .open()

后面设置一个urlencoded标头。
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

其他代码部分是正确的,因为我自己检查过

修改了代码中的错误,使其与更多浏览器兼容。感谢@Mr。@Felix Kling和BeatMasta让我直接在onreadystatechange的位置,发送头和浏览器兼容性问题。

。Javascript:

function sendNews()
{
    var title=document.getElementById("title").innerHTML;
    var body=document.getElementById("boddy").innerHTML;
    var params="title="+title+"&body="+body;
    var xmlhttp;
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    //Send the proper header information along with the request    
    xmlhttp.open("POST","sendnews.php",true);
    xmlhttp.onreadystatechange=function(){
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            document.getElementById("newsAddResult").innerHTML=xmlhttp.responseText;
        }     
    }
    xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xmlhttp.send(params);
}

在你的php中有:

$title=@$_POST['title'];
$body=@$_POST['body'];

应该是:

$title = $_POST['title'];
$body = $_POST['body'];

为什么不试试jQuery呢?这会让你的生活轻松很多。

$('#your-send-button').click(function() {
    $.post('sendnews.php', {
        title: $('#title').html(),
        body: $('#boddy').html()
    }, function(data) {
        $('#newsAddResult').html(data);
    });
});