【发布时间】:2011-11-02 10:49:49
【问题描述】:
我正在构建一个 jquery 移动应用程序,它允许用户通过 json 发布和查看主题。服务器端使用 php 和 mysql 注入来捕获 json 数据。服务器端确实看到了传递的值,并成功地将其注入到 sql 中。问题是它没有运行成功回调结果。
此错误日志显示在 Chrome 的控制台上:"XMLHttpRequest cannot load http://xxxxxxx/newpost.php. Origin null is not allowed by Access-Control-Allow-Origin." 如果我在参数中添加dataType: "jsonp",错误将更改为"Uncaught ReferenceError: SUCCESS is not defined."
这是我的html:
<div data-role="content">
<div data-role="content">
<form id="newPostForm">
<div data-role="fieldcontain">
<label for="postTitle"><strong>Post Title:</strong></label>
<input type="text" name="postTitle" id="postTitle" value="" />
<label for="postContent"><strong>Post Content:</strong></label>
<textarea name="postContent" id="postContent"></textarea>
<fieldset class="ui-grid-a">
<div class="ui-block-a"><a href="#indexPage" id="cancel" data-role="button">Cancel</a></div>
<div class="ui-block-b"><button data-theme="b" id="submit" type="submit">Submit</button></div>
</fieldset>
<h3 id="notification"></h3>
</div>
</form>
</div>
</div>
脚本:
function resetTextFields()
{
$("#postTitle").val("");
$("#postContent").val("");
}
function onSuccess(data, status)
{
resetTextFields();
// Notify the user the new post was saved
$("#notification").fadeIn(2000);
data = $.trim(data);
if(data == "SUCCESS")
{
$("#notification").css("background-color", "#ffff00");
$("#notification").text("The post was saved");
}
else
{
$("#notification").css("background-color", "#ff0000");
$("#notification").text(data);
}
$("#notification").fadeOut(5000);
}
$(document).ready(function() {
$("#submit").click(function(){
var formData = $("#newPostForm").serialize();
$.ajax({
type: "POST",
url: "http://xxxxxxxx/newpost.php",
cache: false,
data: formData,
success: onSuccess
});
return false;
});
$("#cancel").click(function(){
resetTextFields();
});
$("#refresh").click(function(){
location.reload();
});
});
这是 php 代码:
header('Content-type: application/json');
try
{
$connection = mysql_connect("localhost","user","pass");
mysql_select_db("dbtable", $connection);
$postTitle = mysql_real_escape_string($_POST[postTitle]);
$postContent = mysql_real_escape_string($_POST[postContent]);
mysql_query("INSERT INTO weblogins (postTitle, postContent) VALUES ('$postTitle', '$postContent')");
mysql_close($connection);
echo "SUCCESS";
}
catch(Exception $e)
{
echo $e->getMessage();
}
当按下按钮时,客户端没有任何反应,没有通知,但它确实将提交的表单注入到 sql。
我错过了什么?谢谢。
【问题讨论】:
-
您是在 chrome 上进行测试,还是在其他浏览器上进行相同的测试?尝试将
www添加到您的网址或尝试不使用http即/xxxxxxx/newpost.php -
我已经这样做了,但结果是一样的