jQuery AJAX跨域

本文翻译自:jQuery AJAX cross domain

Here are two pages, test.php and testserver.php. 这是两个页面,test.php和testserver.php。

test.php test.php的

<script src="scripts/jq.js" type="text/javascript"></script>
<script>
    $(function() {
        $.ajax({url:"testserver.php",
            success:function() {
                alert("Success");
            },
            error:function() {
                alert("Error");
            },
            dataType:"json",
            type:"get"
        }
    )})
</script>

testserver.php testserver.php

<?php
$arr = array("element1",
             "element2",
             array("element31","element32"));
$arr['name'] = "response";
echo json_encode($arr);
?>

Now my problem: when both of these files are on the same server (either localhost or web server), it works and alert("Success") is called; 现在我的问题是:当这两个文件都在同一台服务器(本地主机或Web服务器)上时,它会工作,并且会调用alert("Success") ; If it is on different servers, meaning testserver.php on web server and test.php on localhost, its not working, and alert("Error") is executing. 如果它位于不同的服务器上,意味着Web服务器上的testserver.php和localhost上的test.php,它不起作用,并且正在执行alert("Error") Even if the URL inside ajax is changed to http://domain.com/path/to/file/testserver.php 即使ajax中的URL更改为http://domain.com/path/to/file/testserver.php


#1楼

参考:https://stackoom.com/question/Ei7k/jQuery-AJAX跨域


#2楼

I had to load webpage from local disk "file:///C:/test/htmlpage.html", call "http://localhost/getxml.php" url, and do this in IE8+ and Firefox12+ browsers, use jQuery v1.7.2 lib to minimize boilerplate code. 我不得不从本地磁盘“file:/// C:/test/htmlpage.html”加载网页,调用“http://localhost/getxml.php”url,并在IE8 +和Firefox12 +浏览器中执行此操作,使用jQuery v1 .7.2 lib最小化样板代码。 After reading dozens of articles finally figured it out. 看了几十篇文章后终于搞清楚了。 Here is my summary. 这是我的总结。

  • server script (.php, .jsp, ...) must return http response header Access-Control-Allow-Origin: * 服务器脚本(.php,.jsp,...)必须返回http响应头Access-Control-Allow-Origin:*
  • before using jQuery ajax set this flag in javascript: jQuery.support.cors = true; 在使用jQuery之前,ajax在javascript中设置了这个标志:jQuery.support.cors = true;
  • you may set flag once or everytime before using jQuery ajax function 你可以在使用jQuery ajax函数之前设置一次或每次标记
  • now I can read .xml document in IE and Firefox. 现在我可以在IE和Firefox中阅读.xml文档了。 Other browsers I did not test. 其他浏览器我没有测试。
  • response document can be plain/text, xml, json or anything else 响应文档可以是plain / text,xml,json或其他任何内容

Here is an example jQuery ajax call with some debug sysouts. 这是一个带有一些调试sysout的jQuery ajax调用示例。

jQuery.support.cors = true;
$.ajax({
    url: "http://localhost/getxml.php",
    data: { "id":"doc1", "rows":"100" },
    type: "GET",
    timeout: 30000,
    dataType: "text", // "xml", "json"
    success: function(data) {
        // show text reply as-is (debug)
        alert(data);

        // show xml field values (debug)
        //alert( $(data).find("title").text() );

        // loop JSON array (debug)
        //var str="";
        //$.each(data.items, function(i,item) {
        //  str += item.title + "\n";
        //});
        //alert(str);
    },
    error: function(jqXHR, textStatus, ex) {
        alert(textStatus + "," + ex + "," + jqXHR.responseText);
    }
});

#3楼

There are few examples for using JSONP which include error handling. 使用JSONP的例子很少,包括错误处理。

However, please note that the error-event is not triggered when using JSONP! 但请注意,使用JSONP时不会触发错误事件! See: http://api.jquery.com/jQuery.ajax/ or jQuery ajax request using jsonp error 请参阅: http//api.jquery.com/jQuery.ajax/使用jsonp错误的jQuery ajax请求


#4楼

It is true that the same-origin policy prevents JavaScript from making requests across domains, but the CORS specification allows just the sort of API access you are looking for, and is supported by the current batch of major browsers. 确实,同源策略阻止JavaScript跨域发出请求,但CORS规范只允许您正在寻找的那种API访问,并且受当前批量主流浏览器的支持。

See how to enable cross-origin resource sharing for client and server: 了解如何为客户端和服务器启用跨源资源共享:

http://enable-cors.org/ http://enable-cors.org/

"Cross-Origin Resource Sharing (CORS) is a specification that enables truly open access across domain-boundaries. If you serve public content, please consider using CORS to open it up for universal JavaScript/browser access." “跨域资源共享(CORS)是一种规范,可实现跨域边界的真正开放访问。如果您提供公共内容,请考虑使用CORS打开它以进行通用JavaScript /浏览器访问。”


#5楼

You can control this via HTTP header by adding Access-Control-Allow-Origin . 您可以通过添加Access-Control-Allow-Origin来通过HTTP标头控制此操作。 Setting it to * will accept cross-domain AJAX requests from any domain. 将其设置为*将接受来自任何域的跨域AJAX请求。

Using PHP it's really simple, just add the following line into the script that you want to have access outside from your domain: 使用PHP非常简单,只需将以下行添加到您希望从域外访问的脚本中:

header("Access-Control-Allow-Origin: *");

Don't forget to enable mod_headers module in httpd.conf. 不要忘记在httpd.conf中启用mod_headers模块。


#6楼

You need to have a look at Same Origin Policy : 您需要查看同源策略

In computing, the same origin policy is an important security concept for a number of browser-side programming languages, such as JavaScript. 在计算中,相同的源策略是许多浏览器端编程语言(如JavaScript)的重要安全概念。 The policy permits scripts running on pages originating from the same site to access each other's methods and properties with no specific restrictions, but prevents access to most methods and properties across pages on different sites. 该策略允许在源自同一站点的页面上运行的脚本在没有特定限制的情况下访问彼此的方法和属性,但阻止访问不同站点上的页面上的大多数方法和属性。

For you to be able to get data, it has to be: 为了能够获取数据,它必须是:

Same protocol and host 相同的协议和主机

You need to implement JSONP to workaround it. 您需要实现JSONP来解决它。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值