使用jQuery获取JSON数据并进行验证

fetch JSON data using jQuery and validate it

本文关键字:验证 数据 jQuery 获取 JSON 使用      更新时间:2023-09-26

我最近一直在使用jQuery,但从未使用过JSON。

现在,我正在服务器端使用PHP准备JSON。我需要使用javascript(使用jQuery的首选方式)获取JSON数据

我可以通过访问下面提到的类似URL来获得JSON数据

http://www.example.com/getjson.php?catid=1        
                    OR
http://www.example.com/getjson.php?catid=15       

我的服务器上有一个文件名"getjson.php",它将接受一个"get"参数作为catid(代表类别id),从类别表中获取数据,并以JSON格式输出数据。

现在我需要JS代码(如果代码在jQuery中,它会增加优势,因为我非常需要jQuery中的代码),它可以从上面提到的URL中获取数据,并对其进行解析(我认为这是在解码JSON,对吧?)

还有一件事,在获取数据后,我需要验证我收到的数据是否为JSON格式(这非常重要)

类别表有以下字段,我以JSON格式输出这些字段。

ID, Name, Description, ImageURL, Active, Deleted

请帮帮我。谢谢

$.ajax({
    dataType: 'json',
    type: 'GET',
    url: 'http://www.example.com/getjson.php?catid=15',
    success: function(data) {
        // data be a javascript object that contains your already decoded json data
    }
});

使用$.getJSON(url,data,callback);

它从给定的url中获取数据,并检查它是否为JSON有效。

$.getJSON(
    'http://www.example.com/getjson.php?catid=' + $('#valueContainer').val(),
     function (data) {
         // do stuff here
     });

您可以使用JQuery get函数来请求服务器页面并传递相关参数。

然后,为了解析您的响应,您可以使用JSON.parse(),如果它返回/抛出错误,则您没有有效的JSON。

注意一旦您的响应通过JSON.parse运行,它将不再是JSON字符串,而是一个JavaScript对象。

您可以使用以下内容来检索JSON:

$.getJSON('http://www.example.com/getjson.php?catid=1', function(data) { // success statement here });

然后,您可以使用jQuery.parseJSON()来验证结果。看见http://api.jquery.com/jQuery.parseJSON/了解更多详细信息。

$.getJSON应该能做到这一点。

$.getJSON("http://www.example.com/getjson.php", {catid:1}, function(data){
    console.log( data ); // display the JSON data in the web console
});

因为$.getJSON返回一个jqXHR对象,所以可以附加一个错误回调,如下所示:

$.getJSON("http://www.example.com/getjson.php", {catid:1}, function(data){
    console.log( data ); // display the JSON *data* in the web console
    // you can then access the params via dot syntax like this:
    var id = data.ID,
        name = data.Name,
        description = data.Description,
        imageURL = data.ImageURL,
        active = data.Active,
        deleted = data.Deleted;
}).error(function(){
     alert("Error!");
});

有趣的事实:每当您使用jQuery for AJAX时,它都会在请求中添加一个值为"XMLHttpRequest"的X-Requested-Wise头。您可以用服务器端的PHP代码检查这个头,并决定是显示HTML页面还是发送回AJAX适当的数据。

当您绑定到链接上的单击事件时,这很有用。但是,当有人直接导航到href时,您希望该链接仍然有效。

<a href="http://www.example.com/getjson.php?catid=1">Category 1</a>    

JS:

$("a").click(function(e){
    // Keep the browser from navigating to the link's href.
    e.preventDefault();
    // Because we are using one of jQuery's AJAX methods we can get data back from 
    // our server that is different than the data we would get if we navigated to
    // the link directly.
    $.getJSON(this.href, /* optional data param */ function(data){
        console.log( data ); // display the JSON data in the web console
    });
});