我发现这个问题,我试图在不离开页面的情况下更新我的数据库。
How to update a mysql database without reloading page
我正在尝试创建Sandeepan Nath发布的脚本。
我所拥有的是一个小编辑。
<script type="text/javascript">
function addItemToUsersList(itemId)
{
$.ajax
({
'url': 'addtofavourit.php',
'type': 'GET',
'dataType': 'json',
'data': {itemid: itemId},
'success': function(data)
{
if(data.status)
{
if(data.added)
{
alert("Item added to your personal list");
}
else
{
alert("This item is already on your list");
}
}
},
'beforeSend': function()
{
alert("Adding item to your bucketlist...");
},
'error': function(data)
{
// this is what happens if the request fails.
alert("An error occureed");
}
});
}
和我的html(由php创建的循环)
<div style="margin-top:40px;">
<a onclick="addItemToUsersList(<?php echo $imgid ?>)" ><b>Add to favourit</b
</a>
</div>
最后,addtofavourit.php的内容与我尝试运行ajax的页面位于同一个文件夹中。
<?php
if($_GET['itemId'] > 1) //just for debugging should always atleast return status true..
{
return json_encode(array("status" => true, "added" => true));
}
else
{
return json_encode(array("status" => true, "added" => false));
}
?>
这样做的结果是我首先得到一个警告框,其中包含“将项目添加到您的清单......”
但在那条消息之后我得到一个新的警告框:
发生错误
我试图将addtofavourit.php更改为 http://www.domain.com/pathto/addtofavourit.php(http://www.domaim.com/pathto/是我的个人网站,仅为示例添加。)和../addtofavourit.php,但它没有帮助。
有人可以帮助我,因为我不知道要看。
答案 0 :(得分:0)
可能是您未向其发送ajax请求的页面(可能存在正确路径问题),尝试使用firebug进行分析,如果您发现ajax请求已转为<强烈>红色颜色表明你的要求有问题!
答案 1 :(得分:-1)
首先在数据类型之前添加ContentType:
(有时这会导致异步调用无法正常工作) contentType:“application / json; charset = utf-8”,
并删除所有参数中的单打引号(网址,类型,成功等)