0

我有一个通过网络服务获得的 Json 结果,现在我想看看它是否有效,我如何使 Json 值显示在按钮或链接中?和页面加载?

返回的值之一如下所示:“name”:“Muhammad Ali”,“nickname”:“The Greatest”,

对 json 和 javcascript 来说非常新。

Javascript 和 json :

    function Getdata() {
    $.ajax({
        type: "POST",
        data: "{}",
        url: "https://raw.github.com/appcelerator/Documentation-Examples/master/HTTPClient/data/json.txt",
        contentType: "application/json; cherset=utf-8",
        datatype: "json",
        success: loadpage,
        failure: givealert
    });



    function loadpage(result) {
        if (resu.hasOwnProperty("d")) { result = res.d; }
        var data = JQuery.parseJSON(result);
    }

    function givealert(error) {
        alert('failed!!' + error);
    }
}

现在我如何让它在标签和表单加载时显示来自 Web 服务的一个值?标签/按钮的 html 标记:

 <div id="listheight">
                <a type="button" id="routing" href="#datatapage"></a>
            </div>

我正在使用 cordova/phonegap、Visual studi2010、html、javascript、css、jquerymobile 和 jquery1.8.2。

提前致谢!

4

1 回答 1

1

首先,使用这个 HTML

<a type="button" id="routing" href="#datatapage" onclick="Getdata()">Click</a> 

使用此代码在页面加载时自动调用该方法

$(document).ready(function() {
  // this is executed on page load
  Getdata();
});

并将您的代码更改为

jQuery.support.cors = true;

function Getdata() {
  var request = $.ajax({
    type: "POST",
    data: "{}",
    dataType: 'json',
    url: "data/json.txt",  // better use a relative url here
    mimeType: "application/json; cherset=utf-8",
    success: loadpage,
    failure: givealert
  });

  function loadpage(result) {
    // this only displays you the values in a messagebox for you to check if it works
    // you can remove the following two lines
    alert("Name = "+result.fighters[0].name);
    alert("Nickname = "+result.fighters[0].nickname);
    // this changes the text
    document.getElementById("routing").innerHTML = result.fighters[0].name;
  }

  function givealert(error) {
    alert('failed!!' + error);
  }
}

我为此创建了一个 JSFiddle:http: //jsfiddle.net/FUWyJ/ 请注意,我发送请求的 URL 由 JSFiddle 提供,并指向我复制的https://gist.github.com/4001105你的样本数据。

于 2012-11-01T07:53:23.817 回答