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

发布于 2024-12-26 17:56:07 字数 5153 浏览 0 评论 0原文

我从 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);
    }
}

谢谢,

最诚挚的问候, 多发性硬化症

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

我ぃ本無心為│何有愛 2025-01-02 17:56:07

你得到的不是 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 之间的区别,维基百科 JSONP 来救援

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

这个 StackOverflow 问题也解决了这个问题:JSONP 是什么?

因此,使用 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 + ");");

What you've got there isn't JSON, but javascript. To use this, you want to add a:

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

to your html. Then jsonData will be a global object, so you can simply refer to:

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

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:

$.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); }
});

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:

Requests for JSONP retrieve not JSON, but arbitrary JavaScript code.
They are evaluated by the JavaScript interpreter, not parsed by a JSON
parser.

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:

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

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:

function processJsonData(data) { ... }

Note that for this to work with jQuery, you need to change your ajax call:

$.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); }
});

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:

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

to:

    Response.Write("processJsonData(" + strResult + ");");
玻璃人 2025-01-02 17:56:07

建议您查看 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
});

Recommend you look into jQuery .getJson or .ajax.

But as a sample:

$.ajax({
    url: 'url/to/get/json',
    type: "Post",
    success: function (result) {
       //result will contain your json object
       //loop through json and output as HTML
});
兮子 2025-01-02 17:56:07

请确保您已将 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中执行。< /em>

JSONP 用于绕过 XHR 跨域 那个需要包含服务器端脚本。确保您已将回调添加到 JSONP 脚本中。以下是 IBM develperworks 中的资源

顺便说一句:您可以尝试 JSON2JSON2-source 在回调函数中,以确保返回的是 JSON。

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

Please make sure you have added a callback function which defined in js to your JSONP script tag.

For example:

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

Then in your server side script you need to do as following(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);
}

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文