Ajax只有在我将html页面上传到服务器时才有效


Ajax only works when I upload the html-page to my server

当html文件没有上传到我的服务器时,下面的代码返回"error"是正常的吗?如果是,为什么?不过,一旦我把它上传到服务器上,它就会完美地工作。。。

<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
        function validate() {
                    $.ajax({
                        type:'POST',
                        url:'http://www.mywebsite.com/formvalidate.php',
                        data:{
                        },
                        dataType:'json',
                        success:function (data) {
                            alert('success');

                        },
                        error:function (XMLHttpRequest, textStatus, errorThrown) {
                            alert('error');
                        }
                    });
                }
</script>
</head>
<body>
<input type=button onclick="validate();" value="Click me"/>
</body>

由于使用"同源策略",如果在jquery ajax调用上使用jsonp类型,则可以避免这种情况
在您的情况下,您可以,因为您正在编写服务器端和客户端。

原因是不允许跨域ajax,当您从浏览器或本地主机运行此文件时,它正在为ajax调用访问不同的网站url,这是不允许的。

但当你在同一台服务器上上传时,就没有跨域问题,所以成功消息

为了允许跨域ajax调用,您应该使用JSONP

$.ajax({
     url:"testserver.php",
     dataType: 'jsonp', // Notice! JSONP <-- P (lowercase)
     success:function(json){
         // do stuff with json (in this case an array)
         alert("Success");
     },
     error:function(){
         alert("Error");
     },
});

参考文献:-jQuery AJAX跨域

Javascript不是跨域的,所以您需要在同一个域中,或者使用JSONP在加载页面中允许它。

相关文章: