简体   繁体   English

Javascript将JSONP数据从字符串转换为Json对象

[英]Javascript Convert JSONP data from string to Json object

So i am not sure if i am doing this right. 所以我不确定我是否做对了。
I want to send markup over HTML (i am trying to create a widget) Here is the mocky response that i am expecting 我想通过HTML发送标记(我正在尝试创建小部件), 是我期望的模拟响应

so I create a simple jquery get like this 所以我创建了一个简单的jquery这样

var jsonp_url = "http://www.mocky.io/v2/5c9e901a3000004a00ee98a1?callback=myfunction";
    $.ajax({
                    url: jsonp_url,
                    type: 'GET',
                    jsonp: "callback",
                    contentType: "application/json",
                    success: function (data) {
                     $('#example-widget-container').html(data.html)
                    },
                    error: function (data) {
                        alert('woops!'); //or whatever
                    }
                });

then created myFunction 然后创建了myFunction

function myfunction(data) {
        console.log(data);
}

The problem being that while, i get the response it comes as a string instead of a json or function. 问题是,虽然我得到的响应是字符串而不是json或函数。 i am not sure how to extract the json from this (unless i do string manupulation). 我不确定如何从中提取json(除非我进行字符串操作)。 Any pointers would be helpful. 任何指针都会有所帮助。

JSFiddle here JSFiddle 在这里

PS Per https://www.mocky.io/ , PS每个https://www.mocky.io/
Jsonp Support - Add ?callback=myfunction to your mocky URL to enable jsonp. Jsonp支持-在您的模拟URL中添加 ?callback = myfunction以启用jsonp。

  1. Delete function myfunction . 删除function myfunction
  2. In the URL, replace callback=myfunction with callback=? 在URL中,将callback=myfunction替换为callback=? .

jQuery will generate a function (your success function) and a function name for you. jQuery将为您生成一个函数(您的成功函数)和一个函数名。

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

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