[英]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请求,您需要设置一个urlencoded头,将其放在xmlhtt.open()之后
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
我自己检查过的其他代码部分是正确的
进行了修改,以更正代码中的错误并使其与更多浏览器兼容。 感谢@先生。 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'];
您为什么不尝试jQuery ? 这会让您的生活变得轻松多了。
$('#your-send-button').click(function() {
$.post('sendnews.php', {
title: $('#title').html(),
body: $('#boddy').html()
}, function(data) {
$('#newsAddResult').html(data);
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.