我在下面创建了一些示例代码。您只需单击要删除的文本(或li元素)即可删除项目。
当您在删除时查看“网络”标签时,您会同时获得204和200的响应。为什么有两个?我只打1个电话。
请求方法“ OPTIONS”来自何处?
//Cache DOM
var $content = $( 'ul' );
var $name = $( '#name' );
var $bike = $( '#bike' );
var $addButton = $( '#add-item' );
var $liElems = $( 'li' );
//Functions
$( function () {
function addItem( data ) {
$content.append( '<li id="' + data.id + '">' + data.name + ' likes ' + data.bike + '</li>' );
}
$.ajax( {
type: 'GET',
url: 'http://rest.learncode.academy/api/sjm/bikes',
success: function( response ) {
$.each( response, function( index, bikes ) {
addItem( bikes );
});
},
error: function( ) {
console.log ( 'error loading orders' );
}
});
$addButton.on( 'click', function(){
var data = {
name: $name.val(),
bike: $bike.val()
};
$.ajax( {
type: 'POST',
url: 'http://rest.learncode.academy/api/sjm/bikes',
data: data,
success: function( response ) {
addItem( response );
},
error: function( ) {
console.log( 'error while saving' );
}
});
});
$content.delegate( 'li', 'click', function ( ) {
var id = $( this ).attr( 'id' );
var $this = $( this );
console.log ( 'delete ' + id);
$.ajax({
type: 'DELETE',
url: 'http://rest.learncode.academy/api/sjm/bikes/' + id,
success: function( response ){
$this.fadeOut( 300, function ( ) {
remove( );
});
},
error: function( ){
console.log( 'error deleting data' );
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content">
<section>
name <input type="text" id="name">
bike <input type="text" id="bike">
<button id="add-item">add data</button>
</section>
<ul></ul>
</div>
当您尝试将XMLHttpRequest发送到与托管页面不同的域时,您违反了同源策略。但是,这种情况在某种程度上变得很普遍,引入了许多技术。CORS就是其中之一。
简而言之,您正在发送DELETE请求的服务器允许跨域请求。在此过程中,应该有一个预检调用,也就是HTTP OPTION调用。
因此,您对OPTION和DELETE调用有两个响应。
有关CORS的信息,请参见MDN页面。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句