简体   繁体   English

有没有办法通过ajax调用返回由javascript呈现的JSON

[英]Is there a way to return JSON rendered by javascript through ajax call

I have a situation that I have to run some javascript and get a response on a clients site from my site, and I'm trying to think of the best way to do this because of cross domain scripting security. 我有一种情况,我必须运行一些javascript并从我的站点上在客户端站点上获得响应,并且由于跨域脚本安全性,我试图考虑做到这一点的最佳方法。 I have access to placing a snippet of code on a client page. 我有机会获得配售的代码片段客户端页面上。 I can modify my own site as much as I want. 我可以根据需要修改自己的网站。

One option is to open the page up via an iframe have the snippet on their site run get the response and set a cookie that I can poll for to get the response from...yikes... 一种选择是通过iframe打开页面,让其网站上的代码段运行以获取响应,并设置一个cookie,我可以对其进行轮询以从...中获取响应...

I have been thinking of different ways to do this, and I'm trying to get creative. 我一直在想不同的方式来做到这一点,并且我正在尝试发挥创造力。 I'm a backend guy with a bit of javascript experience, but nothing having to deal with cross domain stuff. 我是一个后端家伙有点JavaScript的经验,但不必处理跨域的东西罢了。 Please I would appreciate any help. 请给我任何帮助。 Thanks, 谢谢,

You could use JSONP in your situation. 您可以根据情况使用JSONP

Example with JQuery could be found here 可以在这里找到带有JQuery的示例

在您的代码段位于客户端的情况下,动态创建iframe-然后您将进入客户端域沙箱,并且能够向您的网站发送请求

May be you can call a web service via ajax call and return JSON string by following way.. 可能您可以通过ajax调用来调用Web服务,并通过以下方式返回JSON字符串。

$.ajax({
            type: "POST",
            url: "JSON.asmx/Getdata",
            data: {},
            contentType: "text/javascript; charset=utf-8",
            ContentLength: 15000,
            dataType: "text",
            async: true,
            // timeout:10000,
            success: function (msg) {
                asmxdata(msg);
                return false;
            },
            error: function (xhr, ajaxOptions, thrownError, request, error) {
                alert('xrs.status = ' + xhr.status + '\n' +
                            'thrown error = ' + thrownError + '\n' +
                             'xhr.statusText = ' + xhr.statusText + '\n' +
                            'request = ' + request + '\n' +
                            'error = ' + error);
                return false;

            }
        });

Then on success of the Web service call (ie method asmxdata() in here) you can evaluate the JSON string into a JSON object by following way: 然后,在成功调用Web服务(即此处的方法asmxdata())后,您可以通过以下方式将JSON字符串评估为JSON对象:

function asmxdata(data) {
var JObject = eval('(' + data + ');');
}

and assign values to controls 并将值分配给控件

document.getElementById('lblfirstname').value = JObject.Table[i].FirstName;

If anything is unclear please Comment. 如果不清楚,请发表评论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM