我试图从一个"远程"网站获取一些json数据.

我得到以下信息:

    XMLHttpRequest cannot load http://localhost:99000/Services.svc/ReturnPersons. Origin http://localhost:99001 is not allowed by Access-Control-Allow-Origin.

即使我将网页作为HTML文件启动,我也会收到以下信息:

    XMLHttpRequest cannot load http://localhost:99000/Services.svc/ReturnPersons.Origin null is not allowed by Access-Control-Allow-Origin.

The web service returns data. I try to catch the data items like this:

var url = "http://localhost:99000/Services.svc/ReturnPersons";
$.getJSON(url, function (data) {
success: readData(data)
});
function readData(data) {
    alert(data[0].FirstName);
}

我试图得到这个 struct :

[{"FirstName":"Foo","LastName":"Bar"},{"Hello":"Foo","LastName":"World"}]

Do you know why I'm getting this error?

推荐答案

您不能跨域执行XMLHttpRequest,唯一的" Select "是一种称为JSONP的技术,归根结底是:

To start request: Add a new <script> tag with the remote url, and then make sure that remote url returns a valid javascript file that calls your callback function. Some services support this (and let you name your callback in a GET parameters).

另一个简单的解决方法是在本地服务器上创建一个"代理",它获取远程请求,然后将其"转发"回javascript.

edit/addition:

I see jQuery has built-in support for JSONP, by checking if the URL contains "callback=?" (where jQuery will replace ? with the actual callback method). But you'd still need to process that on the remote server to generate a valid response.

Json相关问答推荐

我可以使用JQ来缩小数组中的json对象的范围吗?

通过在织女星简化图上裁剪来显示文本

规范化JSON数据

将不带正文的 CURL POST 转换为 RESTRequest Delphi 代码 / 为 Dropbox API /get_current_account 端点编写 Delphi 代码

使用 jq 从字符串列表开始创建对象

用于遮蔽卡的 Jolt 规格

在 PostgreSQL 中 Select 分层 JSON 作为表

如何实现一个通用的 serde_json::from_str

使用 Ansible 解析来自 Juniper 交换机的 JSON 输出

如何使用 jackson 反序列化为 Kotlin 集合

如何使用 Newtonsoft.Json 反序列化 JSON 数组

Jackson Json:如何将数组转换为 JsonNode 和 ObjectNode?

在 Rails 中使用 JSON 创建嵌套对象

如何使用 Newtonsoft.Json 包在 C#(4.0) 中解析我的 json 字符串?

ASP.NET MVC 读取原始 JSON 发布数据

从 VS 2017 Azure Function 开发中的 local.settings.json 读取值

如果键可能不存在,则从 Python dict 读取

仅使用字符串和值解析 JSON 对象

类型是接口或抽象类,不能实例化

使用 JSON.NET 序列化/反序列化对象字典