简单的Ajax Post无法正常工作

时间:2014-01-23 11:59:56

标签: javascript ajax jquery

我有一个非常简单的Ajax帖子,它不起作用:

<html>
<body>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>

            var deviceDetails = [];

            deviceDetails.project_title = 'project';
            //deviceDetails.platform = window.device.platform;
            deviceDetails.platform = 'ios';

            $.ajax({
                url: "http://someserver.com/device_api",
                type: "post",
                data: deviceDetails,
                success: function(){
                    alert("success");

                },
                error:   function(model, xhr, options){
                    alert('failed');

                    console.log('response is : ');
                    console.log(xhr.responseText);
                },
            });

</script>

</body>
</html>

服务器只是这样做:     

我可以在Chrome的网络标签中看到帖子的状态已“取消”。我错过了什么?

3 个答案:

答案 0 :(得分:2)

正在发送POST请求,但它没有在服务器上命中我的记录器。我将网址更改为:

url: "http://push.schoolspace.ie/device_api/"

最后带有“/”,这很有用。我认为这与服务器上的.htaccess文件有关。

答案 1 :(得分:0)

您很可能会遇到same origin policy个ajax请求。来自$.ajax

的文档
  

由于浏览器安全限制,大多数“Ajax”请求都遵循相同的原始策略;请求无法从其他域,子域或协议成功检索数据。

答案 2 :(得分:-2)

<script>
$(document).ready(function(){
            var deviceDetails = [];

            deviceDetails.project_title = 'project';
            //deviceDetails.platform = window.device.platform;
            deviceDetails.platform = 'ios';

            var deviceDetailsObject = JSON.stringify(deviceDetails);

            $.ajax({
                url: "http://push.schoolspace.ie/device_api",
                type: "post",
                data: deviceDetailsObject,
                success: function(){
                    alert("success");

                },
                error:   function(model, xhr, options){
                    alert('failed');

                    console.log('response is : ');
                    console.log(xhr.responseText);
                },
            });
})
</script>

您需要将数组转换为JSON对象/字符串(http://api.jquery.com/jquery.post/)。 JSON.stringify()函数为您完成此任务。