为什么ajax不适用于POST方法?

时间:2012-01-01 00:28:12

标签: php javascript ajax

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

使用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 "با موفقیت ارسال شد";

?>

问题出在哪里?

3 个答案:

答案 0 :(得分:2)

好的想通了..要使用ajax发送POST请求,你需要设置一个urlencoded标头,只需放在xmlhtt.open()之后

xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

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

答案 1 :(得分:-1)

编辑以更正代码中的错误并使其与更多浏览器兼容。  感谢@Mr。 BeatMasta和@Felix Kling让我直接放置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'];

答案 2 :(得分:-1)

为什么不试试jQuery?它会让你的生活更轻松。

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