javascript 返回 XML 时使用 JSONP

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3435454/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 01:09:59  来源:igfitidea点击:

Using JSONP when returning XML

javascriptjqueryxmljsonp

提问by patricksweeney

I asked an earlier questionwhich was definitely helpful and let me know about JSONP. However, I see that I have to specify JSONP as the datatype. Now, as far as I know, that is the return type of the data coming back, which would be XML. Can XML be returned using JSONP or am I limited to it coming back as JSONP format? Thanks!

我问了一个较早的问题,这绝对有帮助,让我了解 JSONP。但是,我发现我必须将 JSONP 指定为数据类型。现在,据我所知,这是返回数据的返回类型,即 XML。可以使用 JSONP 返回 XML 还是我仅限于以 JSONP 格式返回?谢谢!

采纳答案by Nick Craver

You're limited to JSONP (and not XML) because of how it works. JSONP turns into this:

由于其工作方式,您只能使用 JSONP(而不是 XML)。JSONP 变成这样:

<script src="myPage?callback=myFunction" type="text/javscript">

So when you take the content, it's effectivelydoing this:

因此,当您获取内容时,它实际上是在执行以下操作:

<script type="text/javascript">
  myFunction({ data: value, data2: value2 });
</script>

What comes back is actual running JavaScript, so it can't be XML, you'll get all sorts of syntax errors, exactlyas you would doing this:

什么回来是实际运行JavaScript,因此它不可能是XML,你会得到各种各样的语法错误,正好,你会做这样的:

<script type="text/javascript">
  <elem>
    <data>value</data>
    <data2>value2</data2>
  </elem>
</script>

As you can imagine, the JavaScript parser isn't going to like that very much, and doesn't know what to do with it. jQuery can parse XML in most cases without any trouble, but if you're using JSONP and it's for cross-domain requests...well JSONP is your only option there, unless you wrote a proxy page on your site that didn't violate same-origin policy rules, and used it as a proxy to fetch the XML through.

可以想象,JavaScript 解析器不会很喜欢那样,也不知道如何处理它。在大多数情况下,jQuery 可以毫无困难地解析 XML,但是如果您使用的是 JSONP 并且它用于跨域请求......那么 JSONP 是您唯一的选择,除非您在您的站点上编写了一个没有违反的代理页面同源策略规则,并将其用作代理来获取 XML。

回答by Anurag

The idea is to send back executable code from the server. Write a jQuery plugin or extend the ajax function to return the XML string as a function parameter.

这个想法是从服务器发回可执行代码。编写一个 jQuery 插件或扩展 ajax 函数,将 XML 字符串作为函数参数返回。

myCallback("
  <root>
    <person>
      <first>John</first>
      <last>Doe</last>
    </person>
  </root>")

The plugin will parse this string to XML and return it back to your actual callback. As far as your callback is concerned, it is unaware of the string -> xmlconversion process.

该插件会将此字符串解析为 XML 并将其返回给您的实际回调。就您的回调而言,它不知道string -> xml转换过程。

Here's an existing implementation.

这是一个现有的实现

The most ideal interface to this with jQuery would be,

jQuery 最理想的接口是,

$.ajax({
    url: 'http://example.com/resource?type=xml',
    dataType: 'xmlp',
    success: function(xml) { .. }
});

but since messing around and rewriting jQuery.ajaxis problematic, you could write this as a separate namespaced plugin itself which will use getScriptunderneath.

但是由于乱七八糟和重写jQuery.ajax是有问题的,您可以将其编写为一个单独的命名空间插件本身,它将getScript在下面使用。

$.myNamespace.ajax({
    ..
});

For this to work, you would need control of the server. The server has to know that XML is requested, and respond with a function call which contains the XML string as a parameter. Assuming the callback name you sent over to the remote server was foo, the server will have to respond with something like:

为此,您需要控制服务器。服务器必须知道请求了 XML,并以包含 XML 字符串作为参数的函数调用进行响应。假设您发送到远程服务器的回调名称是foo,则服务器必须响应如下:

foo("<names><name>..</name></names>")

I think if you were using a browser that supported E4X, then there would be no need to wrap the XML inside a string. The server could simply return the XML as an argument to the callback function:

我认为如果您使用的是支持 E4X 的浏览器,那么就不需要将 XML 包装在字符串中。服务器可以简单地将 XML 作为参数返回给回调函数:

foo(
  <names>
    <name>John Doe</name>
  </names>
)

But unfortunately, E4X is not widely supported yet.

但不幸的是,E4X 尚未得到广泛支持。

回答by Derozer

You can write XML in Javascript function inside in /* comment */and convert this function to text with method functionname.toString()and parsing text between "/*" and "*/" with JSONP's callbackfunction, that works in all old browsers. Example xml_via_jsonp.js:

您可以在 Javascript 函数中编写 XML/* comment */并使用functionname.toString()方法将此函数转换为文本,/**/使用JSONP回调函数解析“ ”和“ ”之间的文本,这适用于所有旧浏览器。示例xml_via_jsonp.js

function myfunc()
{/*
<xml>
<div class="container">
        <div class="panel panel-info col-lg-10 col-lg-offset-1 added-panel">
            <div class="panel-heading">Random1 - Random2</div>
            <div class="panel-body">
                <div>Random3</div>
            </div>
        </div>
    </div>
</xml>
*/}

function callback(func)
{
var myhtml = func.toString();
var htmlstart = myhtml.indexOf('/*');
var htmlend = myhtml.lastIndexOf('*/');
return myhtml.substr(htmlstart+2, htmlend-htmlstart-2);
}