【问题标题】:Ajax - I want to return an error if the variable did not return anythingAjax - 如果变量没有返回任何内容,我想返回错误
【发布时间】:2016-12-02 19:27:55
【问题描述】:

如果 .find() 成功并且数据存在,我的代码会返回一个评级。如果没有找到关于 itemname 的数据,我想返回一个错误。如果文件 nameOfBusiness=Cafe,那么它将返回评级 3,但如果我有 nameOfBusiness=Restaurant,那么它应该返回错误“评级尚未发布。”

我的 xml 格式的数据:

<resultitem>
   <itemname>Cafe</itemname>
   <rating>3</rating>
</resultitem>

我有 ajax 代码:

$.ajax({ 
    type: 'GET',
    url: 'someUrl.xml',
    dataType: 'xml',
    success: function(xml){
        var rating = "";                                
        $(xml).find('resultitem itemname:contains("'+nameOfBusiness+'")').each(function(){
        rating = $(this).parent().find('rating').text()
                if(rating==""){
                    alert("Rating is not published yet.");
                } else {
                    alert(rating);
                }

            });
        }
    });

【问题讨论】:

    标签: jquery html ajax xml


    【解决方案1】:

    类似这样的:

    $.ajax({ 
        type: 'GET',
        url: 'someUrl.xml',
        dataType: 'xml',
        success: function(xml){
            var rating = "";                                
            var found = $(xml).find('resultitem itemname:contains("'+nameOfBusiness+'")');
    
            if (!found.length) { //HERE
                alert('error');
                return;
            }
    
            found.each(function(){
                rating = $(this).parent().find('rating').text();
                if(rating==""){
                    alert("Rating is not published yet.");
                } else {
                    alert(rating);
                }
    
            });
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2020-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-27
      • 2020-09-14
      • 1970-01-01
      • 2018-07-30
      相关资源
      最近更新 更多