[英]jQuery AJAX method not working
我将创建一个页面,用户可以在textarea (index.php)中输入内容。 当用户单击Tweet时,它将获得用户键入的所有文本到页面tweet.php (我使用了jQuery Ajax方法)。 之后,它将重定向到页面show.php
这是我的代码
index.php
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Tweet</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
function save_tweet(text_tweet){
$.ajax
({
type: "POST",
url: "tweet.php",
data: "text="+text_tweet,
success: function(msg)
{
if(msg==1){
window.location.href="show.php";
}else{
alert("Error");
}
}
});
}
$("#tweet").bind('click', function(){
var text_tweet = $("#text_tweet").val();
if(text_tweet==""){
$("#show").html("Blank text");
return;
}else{
$("#show").html("");
save_tweet(text_tweet);
}
});
});
</script>
</head>
<body>
<center>
<textarea name="text_tweet" cols="61" rows="5" id="text_tweet"></textarea>
<br/>
<div id="show"></div>
<br/>
<a href="#" id="tweet">Tweet</a>
</center>
</body>
</html>
tweet.php
<?php
session_start();
if(isset($_POST['text'])){
$_SESSION['text_tweet'] = $_POST['text'];
}
?>
show.php
<?php
session_start();
echo $_SESSION['text_tweet'];
?>
问题是当我在textarea中输入一些文本并单击Tweet时,它将警告错误。 谁能知道是什么问题吗?
预先感谢。
为什么要检查味精是否为1? 您在响应正文中返回1吗? 查看JQuery文档,其成功函数回调描述为:
Type: Function( PlainObject data, String textStatus, jqXHR jqXHR )
您可以记录msg的值,然后查看实际包含的内容。
尝试将代码更改为:
$.ajax
({
type: "POST",
url: "tweet.php",
data: {text: text_tweet},
success: function(msg)
{
if(msg==1 || msg=="1"){
window.location.href="show.php";
}else{
alert("Error");
}
}
});
tweet.php
<?php
session_start();
if(isset($_POST['text'])){
$_SESSION['text_tweet'] = $_POST['text'];
echo 1;
}
?>
尝试
if(msg.length){
window.location.href="show.php";
}else{
alert("Error");
}
在您的ajax中添加数据类型:
dataType: 'text',
在您的ajax代码中添加以上行。 并更改您的下一行:
var text_tweet = $("#text_tweet").val();
与:
var text_tweet = $("#text_tweet").text();
并在您的tweet.php文件中添加以下行:
echo "1";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.