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

查看:25
本文介绍了如何在 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.

推荐答案

要完全理解为什么 跨域 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,我们仍然使用脚本标记来加载真正只是普通 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天全站免登陆