如何使用JQUERY读取JSON对象值并将其添加到HTML中

时间:2012-01-14 06:48:53

标签: jquery c#-2.0 jsonp

我的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&section=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&section=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);
    }
}

由于

最诚挚的问候, MS

3 个答案:

答案 0 :(得分:2)

你所拥有的不是JSON,而是javascript。要使用此功能,您需要添加:

<script src="myscript.js" ></script>

到您的HTML。那么jsonData将是一个全局对象,所以你可以简单地参考:

alert(jsonData.tnf.ci[0].atit)

会提醒Australia Pass

更有可能的是,您要做的是删除返回字符串的jsonData=部分。然后,您可以使用典型的jQuery ajax请求处理数据:

$.ajax({
  url: "your_js_url.aspx",
  dataType: "json",
  success: function(data, textStatus, jqXHR) {
    // process the js object data that will contain your returned data
    },
  error: function(jqXHR, textStatus, errorThrown) { alert(textStatus); }
});

更多细节可以在jQuery的ajax文档中找到:http://api.jquery.com/jQuery.ajax/

要理解json和jsonp之间的区别,Wikipedia JSONP to the rescue

  

JSONP的请求不是JSON,而是任意JavaScript代码。   它们由JavaScript解释器评估,而不是由JSON解析   解析器。

此StackOverflow问题也解决了它:What is JSONP all about?

因此,使用JSON,一个以JSON格式返回原始数据,而使用JSONP,则返回一个将由浏览器的javascript解释器评估的脚本。通常做的是在脚本中进行函数调用。在您的情况下,您可能会返回apsx页面:

processJsonData( { { /*your json data here*/ } } );

问题是,JSON数据是有效的Javascript表示法,这就是JSON和Javascript一起玩得很好的原因。

现在,在您的代码中,您需要实现processJsonData函数:

function processJsonData(data) { ... }

请注意,要使用jQuery,您需要更改ajax调用:

$.ajax({
  url: "your_js_url.aspx",
  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); }
});

现在,关于如何处理processJsonData函数中的数据,以及您将数据作为javascript对象接收,以及如何将其映射到HTML取决于数据以及您希望如何出现。我担心你的json对我来说有点太复杂了,无法猜出你想用它做什么。

要使用您的数据调用processJsonData函数,请更改.cs行:

    Response.Write("jsonData =" + strResult + "");

为:

    Response.Write("processJsonData(" + strResult + ");");

答案 1 :(得分:0)

建议您查看jQuery .getJson或.ajax。

但作为样本:

$.ajax({
    url: 'url/to/get/json',
    type: "Post",
    success: function (result) {
       //result will contain your json object
       //loop through json and output as HTML
});

答案 2 :(得分:0)

请确保您已在js中为JSONP脚本标记添加了回调函数。

例如:

jQuery.getJSON("http://www.yourdomain.com/jsonp/ticker?symbol=IBM&callback=?", 
function(data) {//here is the parser
    alert("Symbol: " + data.symbol + ", Price: " + data.price);
});

然后在您的服务器端脚本中,您需要执行以下操作(java servlet)

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
throws ServletException, IOException {
    String jsonData = getDataAsJson(req.getParameter("symbol"));
    String output = req.getParameter("callback") + "(" + jsonData + ");";

    resp.setContentType("text/javascript");

    PrintWriter out = resp.getWriter();
    out.println(output);
}

实际上服务器端脚本的主要目的是返回一个像“callback(obj)”这样的字符串,而不是需要在JS中执行。

JSONP用于传递需要包含服务器端脚本的XHR cross-origin。确保已将回调添加到JSONP脚本中。以下是IBM develperworks中的Resources

BTW:您可以在回调函数中尝试JSON2JSON2-source,以确保返回的是JSON。

然后自己编写解析器/替换器函数。