简体   繁体   中英

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. 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...

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. Please I would appreciate any help. Thanks,

You could use JSONP in your situation.

Example with JQuery could be found here

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

May be you can call a web service via ajax call and return JSON string by following way..

$.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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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