在jQuery ajax中找不到background-image url

时间:2017-12-13 17:39:58

标签: jquery ajax background-image onerror

我使用jQuery并从PHP脚本中的SQL调用中加载数据。数据加载正常,但我需要一些错误检查,因为有时图像网址有时是有效的。

我的jQuery ajax调用看起来像:

    $.ajax({    //create an ajax request to load properties.
      type: "GET",
      url: "code/phpscript.php",
      data: datastring,
      dataType: "json",   //expect json to be returned
      cache: false,
      success: function(response){
         var arr = JSON.parse(JSON.stringify(response));
         var htmlspecial = " ";
         for(var i =0; i < arr.length; i++){
              ...code
              // sometimes these image urls work sometimes not
              var image = "";
              if (arr[i]['image1'] == "" || arr[i]["image1"].indexOf("noimage") >= 0 || arr[i]["image1"].indexOf("no-image")  >= 0 ) {            
               image = "";
            } else {
               image = "https://images.weserv.nl/?url="+arr[i]['image1'].substr(arr[i]['image1'].indexOf("//"));
            }
             htmlspecial += '<div class="col m6 classname"><div class="backgroundPic" style="background: url(' + image + '), url();">   ... more html
         }
      });

当控制台抛出404错误时,我需要停止这些错误消息。我不想用no-image.png替换图像,因为默认背景为深蓝色。

我尝试了什么?

我尝试过onrorror但是这不适用于style =&#34; background..etc&#34;。 我也尝试过:

    $(".backgroundPic").on("error",function() { 
      $('body').css({
        "background-image": 'url()'

      });alert("error");
    }).on("load",function() {
      $('body').css({
        "background-image": 'url(' + image + ')'
      });
    }).attr("src",image);

这在ajax调用中不起作用。

0 个答案:

没有答案