如何使用 JQUERY 读取 JSON 对象值并将其添加到 HTML 中
我从 ASPX 页面返回到客户端页面,收到以下 JSON 响应。现在我想从中读取值并生成 HTML
jsonData ={ "tnf": { "ci": [ {"atit": "Australia Pass", "img": "\/fr\/english\/Images\/EN_Fly_to_Rio_de_Janeiro_v1_185_tcm233-658117.jpg", "sop": "\/fr\/english\/destinations_offers\/special_offers\/mysite_visit_australia_pass\/mysite_visit_australia_pass.aspx" } ], "elt": [ {"t": "sfp", "value": "More special fares" } ], "f": [ { "a": [ {"c": "Hamburg", "p": "from GBP 469*", "pm": "id=744431#744431", "t": "sfp" }, {"c": "Dubai", "p": "from GBP 559*", "pm": "id=744432#744432", "t": "sfp" }, {"c": "Thiruvananthapuram", "p": "from GBP 559*", "pm": "id=744433#744433", "t": "sfp" }, {"c": "Johannesburg", "p": "from GBP 559*", "pm": "id=744434#744434", "t": "sfp" }, {"c": "Beijing", "p": "from GBP 1,780*", "pm": "id=744435#744435", "t": "sfp" }, {"c": "Guangzhou", "p": "from GBP 469", "pm": "pub=\/fr\/english&pageurl=\/IBE.aspx§ion=IBE&TID=SB&resultby=2&j=f&showpage=true&seldcity1=LHR&selacity1=JNB&selddate1=08%20Dec%2011&seladate1=09%20Dec%2011&bsp=Special+Fares+Widget&selcabinclass=0&showsearch=true", "t": "ffp" }, {"c": "Manila", "p": "from GBP 559*", "pm": "id=744437#744437", "t": "sfp" }, {"c": "Kuala Lumpur", "p": "from GBP 559*", "pm": "id=744438#744438", "t": "sfp" } ], "d": [ {"t": "sfp", "value": "From London Heathrow (LHR)" } ] } ], "nof": [ { "a": [ {"class": "bodyLink", "href": "\/sn\/english\/destinations_offers\/special_offers\/special_offers.aspx", "title": "Special Offers", "value": "Special Offers" } ], "value": [ "We don’t have any Special Fares at the moment. Please check again another time, or see our current", "." ] } ], "tc": "Conditions apply for each fare. Dublin commence from 9th January 2012.", "u": [ {"ffp": "\/SessionHandler.aspx", "ffpm": "pageurl=\/IBE.aspx&pub=\/fr\/english§ion=IBE&j=f&bsp=Special+Fares+Widget", "ot": "\/fr\/english\/destinations_offers\/special_offers\/mysite_visit_australia_pass\/mysite_visit_australia_pass.aspx", "sfp": "\/fr\/english\/destinations_offers\/special_offers\/special_fares\/special_fares.aspx" } ] }}
请建议我如何读取它表明我可以轻松地将其添加到我的 HTML
编辑:
这是我用来获取这些值的 Jquery 代码:
$(document).ready(function() {
$('#btnSearch').click(function() {
var strInput = "";
var strSearchType = $('#ddnSearchType').val();
strInput = strInput + "?q=" + strSearchType;
var serviceReq = "http://localhost:2853/jsonproxy/jsonprxy.aspx";
$.ajax({
url: serviceReq + strInput,
dataType: "jsonp",
jsonpCallback: "processJsonData",
success: function(data, textStatus, jqXHR) {
// don't do anything here, since the processing happened in callback function
},
error: function(jqXHR, textStatus, errorThrown) { alert(textStatus); }
});
});
function processJsonData(data) {
alert(data);
$.each(data, function(i, tnf) {
alert(tnf.nof[0].a[0].href)
alert(tnf.elt[0].value)
alert(tnf.f[0].a.c);
$.each(tnf.f[0].a, function(j, adata) {
alert(adata.c);
alert(adata.pm)
});
});
}
});
我可以看到HTTPFox 工具中的三个 GET 变量,
q even
callback processJsonData
_ 1326530518049
它给出解析器错误以及“processJsonData”函数无法识别。
从我的CS返回的结果如上。
下面是我用来获取 JSON 的代码,
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.IO;
using System.Runtime.Serialization.Json;
public partial class jsonProxy : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string strResult = "";
string strSearch = "";
try
{
if (Request.QueryString.Count != 0 && Request.QueryString["q"] != string.Empty)
{
strSearch = Request.QueryString["q"];
}
strResult = performSearch(strSearch);
}
catch
{
strResult = performSearch("");
}
Response.Clear(); //optional: if we've sent anything before
Response.ContentType = "text/html"; //must be 'text/xml'
Response.ContentEncoding = System.Text.Encoding.UTF8; //we'd like UTF-8
Response.Write("jsonData =" + strResult + "");
Response.End(); //optional: will end processing
}
private string performSearch(string strSearch)
{
string returnStr = "";
XmlDocument docXml = new XmlDocument();
docXml.Load("xml/SpecialFares.xml");
returnStr = XmlToJson.XmlToJSON(docXml);
return (returnStr);
}
}
谢谢,
最诚挚的问候, 多发性硬化症
I have got below JSON response from my ASPX page back to my client page. Now I want to read the values from it and want to generate the HTML
jsonData ={ "tnf": { "ci": [ {"atit": "Australia Pass", "img": "\/fr\/english\/Images\/EN_Fly_to_Rio_de_Janeiro_v1_185_tcm233-658117.jpg", "sop": "\/fr\/english\/destinations_offers\/special_offers\/mysite_visit_australia_pass\/mysite_visit_australia_pass.aspx" } ], "elt": [ {"t": "sfp", "value": "More special fares" } ], "f": [ { "a": [ {"c": "Hamburg", "p": "from GBP 469*", "pm": "id=744431#744431", "t": "sfp" }, {"c": "Dubai", "p": "from GBP 559*", "pm": "id=744432#744432", "t": "sfp" }, {"c": "Thiruvananthapuram", "p": "from GBP 559*", "pm": "id=744433#744433", "t": "sfp" }, {"c": "Johannesburg", "p": "from GBP 559*", "pm": "id=744434#744434", "t": "sfp" }, {"c": "Beijing", "p": "from GBP 1,780*", "pm": "id=744435#744435", "t": "sfp" }, {"c": "Guangzhou", "p": "from GBP 469", "pm": "pub=\/fr\/english&pageurl=\/IBE.aspx§ion=IBE&TID=SB&resultby=2&j=f&showpage=true&seldcity1=LHR&selacity1=JNB&selddate1=08%20Dec%2011&seladate1=09%20Dec%2011&bsp=Special+Fares+Widget&selcabinclass=0&showsearch=true", "t": "ffp" }, {"c": "Manila", "p": "from GBP 559*", "pm": "id=744437#744437", "t": "sfp" }, {"c": "Kuala Lumpur", "p": "from GBP 559*", "pm": "id=744438#744438", "t": "sfp" } ], "d": [ {"t": "sfp", "value": "From London Heathrow (LHR)" } ] } ], "nof": [ { "a": [ {"class": "bodyLink", "href": "\/sn\/english\/destinations_offers\/special_offers\/special_offers.aspx", "title": "Special Offers", "value": "Special Offers" } ], "value": [ "We don’t have any Special Fares at the moment. Please check again another time, or see our current", "." ] } ], "tc": "Conditions apply for each fare. Dublin commence from 9th January 2012.", "u": [ {"ffp": "\/SessionHandler.aspx", "ffpm": "pageurl=\/IBE.aspx&pub=\/fr\/english§ion=IBE&j=f&bsp=Special+Fares+Widget", "ot": "\/fr\/english\/destinations_offers\/special_offers\/mysite_visit_australia_pass\/mysite_visit_australia_pass.aspx", "sfp": "\/fr\/english\/destinations_offers\/special_offers\/special_fares\/special_fares.aspx" } ] }}
Please suggest how can I read it show that I can easily add it to my HTMLs
EDIT:
This the Jquery code which I am using to get these values:
$(document).ready(function() {
$('#btnSearch').click(function() {
var strInput = "";
var strSearchType = $('#ddnSearchType').val();
strInput = strInput + "?q=" + strSearchType;
var serviceReq = "http://localhost:2853/jsonproxy/jsonprxy.aspx";
$.ajax({
url: serviceReq + strInput,
dataType: "jsonp",
jsonpCallback: "processJsonData",
success: function(data, textStatus, jqXHR) {
// don't do anything here, since the processing happened in callback function
},
error: function(jqXHR, textStatus, errorThrown) { alert(textStatus); }
});
});
function processJsonData(data) {
alert(data);
$.each(data, function(i, tnf) {
alert(tnf.nof[0].a[0].href)
alert(tnf.elt[0].value)
alert(tnf.f[0].a.c);
$.each(tnf.f[0].a, function(j, adata) {
alert(adata.c);
alert(adata.pm)
});
});
}
});
I can see three GET variables in the HTTPFox tool,
q even
callback processJsonData
_ 1326530518049
Its giving parser error as well as "processJsonData" function is not recognized.
and the result which is returned back from my CS is as above.
Below is code which I am using to get the JSON
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.IO;
using System.Runtime.Serialization.Json;
public partial class jsonProxy : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string strResult = "";
string strSearch = "";
try
{
if (Request.QueryString.Count != 0 && Request.QueryString["q"] != string.Empty)
{
strSearch = Request.QueryString["q"];
}
strResult = performSearch(strSearch);
}
catch
{
strResult = performSearch("");
}
Response.Clear(); //optional: if we've sent anything before
Response.ContentType = "text/html"; //must be 'text/xml'
Response.ContentEncoding = System.Text.Encoding.UTF8; //we'd like UTF-8
Response.Write("jsonData =" + strResult + "");
Response.End(); //optional: will end processing
}
private string performSearch(string strSearch)
{
string returnStr = "";
XmlDocument docXml = new XmlDocument();
docXml.Load("xml/SpecialFares.xml");
returnStr = XmlToJson.XmlToJSON(docXml);
return (returnStr);
}
}
Thanks
Best Regards,
MS
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你得到的不是 JSON,而是 javascript。要使用它,您需要
在 html 中添加一个:。那么
jsonData
将是一个全局对象,因此您可以简单地引用:这将提醒
Australia Pass
。更有可能的是,您想要删除返回字符串的
jsonData=
部分。然后您可以使用典型的 jQuery ajax 请求处理数据:更多详细信息可以在 jQuery 的 ajax 文档中找到: http://api.jquery.com/jQuery.ajax/
要了解 json 和 jsonp 之间的区别,维基百科 JSONP 来救援:
这个 StackOverflow 问题也解决了这个问题:JSONP 是什么?。
因此,使用 JSON 时,会返回 JSON 格式的原始数据,而使用 JSONP 时会返回一个脚本,该脚本将由浏览器的 javascript 解释器进行评估。通常所做的就是在脚本中进行函数调用。在您的情况下,您可能会返回 apsx 页面:
事实是,JSON 数据是有效的 Javascript 表示法,这就是 JSON 和 Javascript 能够如此完美地协同工作的原因。
现在,在您的代码中,您需要实现
processJsonData
函数:请注意,为了与 jQuery 配合使用,您需要更改您的 ajax 调用:
现在介绍如何处理
中的数据processJsonData
函数,好吧,您以 JavaScript 对象的形式接收数据,如何将其映射到 HTML 取决于数据以及您希望其显示的方式。恐怕你的 json 有点太复杂了,我无法猜测你想用它做什么。要使用您的数据调用
processJsonData
函数,请将 .cs 行:更改为:
What you've got there isn't JSON, but javascript. To use this, you want to add a:
to your html. Then
jsonData
will be a global object, so you can simply refer to:which will alert
Australia Pass
.More likely, what you want to do is to remove the
jsonData=
part of the returned string. Then you can handle the data with a typical jQuery ajax request:More details can be found on jQuery's ajax documentation: http://api.jquery.com/jQuery.ajax/
To understand the difference between json and jsonp, Wikipedia JSONP to the rescue:
This StackOverflow question also addresses it: What is JSONP all about?.
So with JSON, one returns the raw data in JSON format, while with JSONP one returns a script that will be evaluated by the browser's javascript interpreter. What one generally does is to make a function call in the script. In your case, you might have your apsx page return:
The thing is, JSON data is valid Javascript notation, which is why JSON and Javascript play together so nicely.
Now, in your code you need to implement the
processJsonData
function:Note that for this to work with jQuery, you need to change your ajax call:
Now as to how to process the data in your
processJsonData
function, well, you're receiving your data as a javascript object, and how you map that to HTML depends on the data and how you want it to appear. I'm afraid your json is a little too complex for me to be able to guess what you're wanting to do with it.To call the
processJsonData
function with your data, change your .cs line:to:
建议您查看 jQuery .getJson 或 .ajax。
但作为一个样本:
Recommend you look into jQuery .getJson or .ajax.
But as a sample:
请确保您已将 js 中定义的回调函数添加到 JSONP 脚本标记中。
例如:
然后在您的服务器端脚本中,您需要执行以下操作(java servlet)
实际上,服务器端脚本的主要目的是返回一个像“callback(obj)”这样的字符串,而不需要在JS中执行。< /em>
JSONP 用于绕过 XHR 跨域 那个需要包含服务器端脚本。确保您已将回调添加到 JSONP 脚本中。以下是 IBM develperworks 中的资源。
顺便说一句:您可以尝试 JSON2 和 JSON2-source 在回调函数中,以确保返回的是 JSON。
然后自己编写解析器/替换器函数。
Please make sure you have added a callback function which defined in js to your JSONP script tag.
For example:
Then in your server side script you need to do as following(java servlet)
Actually the server side script's main purpose is to return a string like "callback(obj)" than need to be execute in JS.
JSONP is used to by pass XHR cross-origin that need to include serverside script. Make sure you have already added the callback to your JSONP script. Here are Resources in IBM develperworks.
BTW: You can have a try JSON2 and JSON2-source in your callback function to make sure the returned is JSON.
And then write the parser/replacer function yourself.