简体   繁体   English

如何避免Ajax跨域请求上的JavaScript错误

[英]How to avoid javascript error on ajax cross domain request

How is it possible to avoid or catch the javascript error without the script to break? 在脚本不中断的情况下如何避免或捕获JavaScript错误?

returns error (empty output) 返回错误(空输出)

$.ajax({
    type : 'GET',
    dataType : 'jsonp',
    url : '//cvrapi.dk/api?search=dsfsdfsd&country=dk',
    success : function(res){
        if(success){
            success(res);
        }
    }
});

no error is returned (with output) 没有错误返回(带有输出)

$.ajax({
    type : 'GET',
    dataType : 'jsonp',
    url : '//cvrapi.dk/api?search=test&country=dk',
    success : function(res){
        if(success){
            success(res);
        }
    }
});

The first one returns a 404 status on the request so you can use fail() to catch the bad request and check status: 第一个在请求上返回404状态,因此您可以使用fail()捕获错误的请求并检查状态:

 $.ajax({ type: 'GET', dataType: 'jsonp', url: '//cvrapi.dk/api?search=dsfsdfsd&country=dk', success: function(res) { if (success) { success(res); } } }).fail(function(err) { console.log('Something went wrong'); // check various status as documented by API if (err.status === 404) { console.log('Not found') } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM