如何在jQuery中解析XML跨域? [英] How to Parse XML Cross-domain in jQuery?

查看:83
本文介绍了如何在jQuery中解析XML跨域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从其他服务器/域解析XML时,如何解决跨域问题?有人可以给我一个例子吗?该示例并不仅限于jQuery,因为JavaScript也足够.

How would I go around the cross-domain issue when parsing XML from a different server/domain? Could someone provide me with an example? The example doesn't have to be restricted to jQuery only, as JavaScript will also suffice.

推荐答案

要完全理解为什么 pure 跨域XML无法正常工作,它有助于首先了解如何促进跨域JSON.

To fully understand why pure cross-domain XML will not work, it helps to first look at how cross domain JSON is facilitated.

首先,让我们看一下在jQuery中提出AJAX请求时会发生什么:

First, let's look at what happens when you make an AJAX request in jQuery:

$.ajax({
    url: '/user.php?userId=123',
    success: function(data) {
        alert(data); // alerts the response
    });

在上面的示例中,相对于域提出了AJAX请求.我们知道,如果尝试在路径之前添加其他域,则请求将失败,并出现安全异常.

In the above example, the AJAX request is made relative to the domain. We know that if we attempt to add a different domain before the path, the request will fail with a security exception.

但是,这并不是说浏览器无法向另一个域发出请求.这是您可能熟悉的示例:

However, that's not to say that the browser cannot make requests to another domain. Here is an example that may be familiar to you:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

根据我们在页面上如何导入JavaScript的知识,我们看到可以加载另一个域上存在的资源!

Based on our knowledge of how to import JavaScript on the page, we see that it is possible to load a resource that exists on another domain!

JSONP是利用此知识的概念. JSONP代表带填充的JSON",它的成功取决于JavaScript对象可以使用字符串表示法表示,以及JavaScript脚本标签可以从外部域加载和运行内容的事实.

JSONP is a concept that exploits this knowledge. JSONP stands for "JSON with padding", and it's success hinges on the fact that JavaScript Objects can be expressed using a string notation, and the fact that JavaScript script tags can load and run content from external domains.

在幕后,jQuery的JSONP看起来像这样,尽管可能不准确:

Under the hood, jQuery's JSONP looks something like this although it may not be exact:

// programmatically load a script tag on the page using the given url
function loadRemoteData(url) {
    var script = document.createElement("script");
    script.setAttribute("type","text/javascript");
    script.setAttribute("src", url);
    document.getElementsByTagName("head")[0].appendChild(script);
}

此外,在页面的某个地方,我们定义了一个回调处理程序:

Also, on the page somewhere, we define a callback handler:

function processData(jsonResult) {
    alert(JSON.stringify(jsonResult)); //alert the JSON as a string
}

在这里,我们发出请求:

Here, we make the request:

// make a request for the data using the script tag remoting approach.
loadRemoteData("http://example.com/users.php?userId=123&callback=processData");

要使其正常工作,我们的PHP脚本必须都以JSON格式返回数据,并且还必须以JavaScript函数名称的形式在字符串周围添加填充",我们可以将其作为参数传入(即回调")

For this to work properly, our PHP script must both return the data in JSON format, and it must also add "padding" around the string in the form of a JavaScript function name that we may pass in as a parameter (i.e. "callback")

因此,如果我们要在Firebug或Chrome NET标签中查看服务器的响应,则该响应可能类似于:

Thus, the response from the server may look something like this, if we were to look at it in the Firebug or Chrome NET tab:

processData( { "userId" : "123" , "name" : "James" , "email" : "example@example.com" } );

因为我们知道JavaScript内容在下载后立即运行,所以我们前面定义的processData函数将立即被调用并作为参数传递给我们的JSON字符串.然后使用JSON.stringify将对象转换回字符串,从而发出警报.

Because we know JavaScript content runs as soon as it's downloaded, our processData function we defined earlier is immediately called and is passed our JSON string as a parameter. It is then alerted, using JSON.stringify to convert the object back into a string.

由于它是一个对象,因此我也可以访问它的属性,如下所示:

Since it's an object, I could also access it's properties, like so:

function processData(jsonResult) {
    alert(JSON.stringify(jsonResult)); //alert the JSON as a string

    // alert the name and email
    alert("User name is " + jsonResult.name + " and email is " + jsonResult.email);
}

最后,让我们进入一个主要问题:可以使用JSONP来获取XML,还是可以解析XML跨域?正如其他人指出的那样,答案是肯定的,但让我们通过一个例子来看看为什么:

Finally, let's move onto the main question: Can JSONP be used to fetch XML, or can we parse XML cross-domain? The answer, as others have pointed out, is a resounding NO, but let's look at why by using an example:

processData(<?xml version="1.0"><user><userid>12345</userid><name>James</name><email>example@example.com</email></user>);

现在,如果将原始XML传递到函数中会发生什么?它将崩溃,因为JavaScript无法将XML转换为JSON.

Now, what will happen if raw XML is passed into the function? It will break, as JavaScript has no way to convert XML into JSON.

但是,假设我们将XML放在引号中

However, suppose we put the XML in quotes:

processData("<?xml version="1.0"><user><userid>12345</userid><name>James</name><email>example@example.com</email></user>");

现在,在此示例中,jsonResult变量实际上采用了一个字符串,我们可以使用它.使用一些JavaScript XML解析工具,我们可以将该字符串加载到XML DOM解析器中并对其进行处理!

Now, in this example, the jsonResult variable actually takes a string, which we can work with. Using some JavaScript XML parsing utilities, we could load that string into the XML DOM Parser and do stuff with it!

但是,它不是纯XML,仍然是底层的JavaScript响应.来自PHP服务器的响应类型仍然是text/javascript,并且我们仍在使用script标签加载实际上只是纯JavaScript的内容.

However, it's not pure XML, it's still a JavaScript response under the hood. The response type from the PHP server is still text/javascript, and we're still using a script tag to load what is really just plain JavaScript.

总而言之,您可以使用"XMLP"或带填充的XML(我刚刚弄清楚,这不是真的!),但是如果您要经历实际上修改响应以返回的所有麻烦,函数回调包装器,您也可以将输出转换为JSON,让浏览器自动和本地处理转换,从而省去了使用XML解析器的麻烦.

In summary, you could work with "XMLP" or XML with padding (I just made that up, it's not real!), but if you're going to go through all of the trouble of actually modifying your response to return a function callback wrapper, you may as well just convert your output to JSON and let the browser handle conversions automatically and natively and save yourself the trouble of having to use an XML parser.

但是如果出于某种原因将数据保留为XML格式更容易,则可以修改响应并为其提供JavaScript包装器.

But if for some reason it's easier to keep your data in XML format, you could modify the response and give it a JavaScript wrapper.

在这种情况下有用的情况可能是,如果您将旧应用程序中的XML数据存储在数据库中,然后使用脚本标签远程处理或JSONP调用将其返回给客户端.

Cases where I could see this being useful might be if you have XML data from a legacy application stored in a database, and you return it to the client-side using script-tag remoting or JSONP calls.

这篇关于如何在jQuery中解析XML跨域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆