Ajax if语句请求

时间:2015-12-03 23:57:24

标签: javascript jquery ajax

$("#Submit").click(function(event){
    event.preventDefault();
    var th = '<tr><th>' + "Business" +'</th><th>' + "Address"+ '</th><th>'+ "Rating" + '</th><th>' + "Date" + '</th></tr>';
    $("#restaurants").empty().html(th);
    var Searching = $("#Search").val();
    $.ajax({
        type     : "GET",
        url      : "http://www.cs.kent.ac.uk/people/staff/lb514/hygiene/hygiene.php",
        dataType : "json",
        data     : {op : "searchname", name : Searching},
        success  : function(data){
            $.each(data,function(key,results){
                if(results.length > 1){
                    $("#restaurants").append(
                        "<tr><td>" + results.business +"</td>"+
                        "<td>" + results.address + "</td>" + 
                        "<td>" + results.rating + "</td>" + 
                        "<td>" + results.date + "</td></tr>"
                    )
                }else if( results.length  <  1){
                    alert("The search term ");
                }
            })
        }
    });
})

这是一个AJAX请求,在用户按下提交按钮搜索餐馆后调用。现在为了更好的设计,我添加了if语句来检查回调对象是否为空但它不起作用 然而,即使有了这个,我已经测试了,如果你给一个餐馆提供一个类似的名字,它也可以。但是如果你给出一个不在数据库中的名字并且我没有看到我出错的地方,它就不会发出警报。

PS。我也试过data.length

1 个答案:

答案 0 :(得分:0)

拥有一个完整的工作示例通常很有帮助,所以这是我的去处。如果您的结果为0,则以下为您提供回复的部分。虽然这并未涵盖所有用例,因为您访问的php文件的工作方式并非100%明显。

var logo = function (searchTerm, callback, message, name) {
    var searchUrl = 'https://ajax.googleapis.com/ajax/services/search/images'     +
        '?v=1.0&q=' + encodeURIComponent(searchTerm);
    var x = new XMLHttpRequest();
    x.open('GET', searchUrl);

    // The Google image search API responds with JSON, so let Chrome parse it.
    x.responseType = 'json';

    x.onload = function() {
        // Parse and process the response from Google Image Search.
        var response = x.response;
        if (!response || !response.responseData || !response.responseData.results ||
            response.responseData.results.length === 0) {
            console.log( "loading error" )
            console.log(response)
            console.log(response.responseData)
            console.log(response.responseData.results)
        }
        var firstResult = response.responseData.results[0];
        // Take the thumbnail instead of the full image to get an approximately
        // consistent image size.
        var imageUrl = firstResult.tbUrl;
        var width = parseInt(firstResult.tbWidth);
        var height = parseInt(firstResult.tbHeight);

        console.assert(
            typeof imageUrl == 'string' && !isNaN(width) && !isNaN(height),
            'Unexpected respose from the Google Image Search API!');
        callback(imageUrl, width, height, message, name);
    };
    x.onerror = function() {
      alert("error")
         document.writeln("network error");
    };
    x.send();
}

相关问题