JSONP如何检索文本 [英] JSONP how to retrieve text

查看:91
本文介绍了JSONP如何检索文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确实了解 的功能,但我不是程序员,也不知道如何提取简单的基础知识.我已经阅读了很多有关JSONP的文章,以及有关JSONP的各种用法的许多示例,但是我还没有找到一个简单的示例来从另一个页面中检索文本(例如http://www.domain.com/external/text.aspx).

I do understand what JSON/JSONP does, but I'm not a programmer and do not know how to extract the bare basics for simple usage. I've read a lot on JSONP and lots of examples on various usage for JSONP, but I have yet to find a simple example for retrieving text from another page (e.g. http://www.domain.com/external/text.aspx).

有人可以举一个将文本检索到div中的jQuery/JSONP设置示例吗? 我认为这是JSONP的非常基本的用法.

Could somebody please give an example of a jQuery/JSONP setup for retrieving text into a div? I would think that is a very basic use of JSONP.

推荐答案

首先,重要的是要了解,要使JSONP正常工作,服务器必须知道将与JSONP请求联系.换句话说,您不能只向某个随机服务器发出请求,并期望如果服务器准备不充分,该请求就可以正常工作.

First, it's important to understand that for JSONP to work, the server must know that it's going to be contacted with a JSONP request. In other words, you can't just make a request to some random server and expect it to work if the server is not prepared properly.

如果您确实知道服务器的URL旨在接受和响应JSONP请求,那么它将返回给您的是包装在函数调用中的JSON表达式.您的页面将包含该函数,因此,当结果从服务器返回时,浏览器将解释JSON表达式,然后调用该函数.

If you do know of a server with a URL that is designed to accept and respond to JSONP requests, then what it will return to you is a JSON expression wrapped in a call to a function. Your page will include that function, and so when the results come back from the server the browser will interpret the JSON expression and then invoke the function.

因此,如果您要创建一个返回漂亮文本块的服务,则将按以下方式调用该服务:

Thus, if you want to make a service that returns a nice block of text, you'll invoke the service like this:

$.getJSON("http://www.domain.com/external/text.aspx?callback=", function(data) {
  $('#targetDiv').text(data.text);
});

jQuery代码将准备一切,以便服务器(通过HTTP请求中名为"jsonp"的参数)被告知要调用的函数的名称(而jQuery本身将为您构建该函数).服务器应使用以下内容进行响应:

The jQuery code will prepare everything such that the server will be told (via a parameter called "jsonp" in the HTTP request) the name of the function to call (and jQuery itself will build that function for you). The server should respond with something like this:

jqueryFunctionName({text: "This is a nice block of text."})

这篇关于JSONP如何检索文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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