2014-05-22 47 views
-1

我想从我的本地json文件加载数据与jquery文章。但它不适用于我,但当我将$ .post()替换为$ .ajax()时,下面的代码工作正常。但我只想用jQuery Post发布。我在控制台中得到(失败)net :: ERR_FILE_NOT_FOUND。jquery后不工作?

<!DOCTYPE html> 
<html> 
<head>  
<script src="jquery-2.1.1.js" type="text/javascript"></script> 
<script type="text/javascript"> 
$(document).ready(function() { 

    $("#ajx").click(function(){ 
     $.post({ 
      type:"POST", 
      dataType:"JSON", 
      data:{}, 
     url: 'ajax_info.json', 
     beforeSend:function(){ 
     alert("before ajax"); 
     },   
     success:function(data){ 

      console.log(data); 

     },error: function(jqXHR, exception) { 
      if (jqXHR.status === 0) { 
       alert('Not connect.\n Verify Network.'); 
      } else if (jqXHR.status == 404) { 
       alert('Requested page not found. [404]'); 
      } else if (jqXHR.status == 500) { 
       alert('Internal Server Error [500].'); 
      } else if (exception === 'parsererror') { 
       alert('Requested JSON parse failed.'); 
      } else if (exception === 'timeout') { 
       alert('Time out error.'); 
      } else if (exception === 'abort') { 
       alert('Ajax request aborted.'); 
      } else { 
       alert('Uncaught Error.\n' + jqXHR.responseText); 
      } 
     } 

     }); 

    }); 
}); 
</script> 

</head> 
<body> 

<input type="button" id="ajx" value="Load File Content"> 


</body> 
</html> 
+0

看看的API在http://api.jquery.com/jQuery.post/ –

+0

类型属性不可用在$ .post http://api.jquery.com/jquery.post/ –

回答

2

$.post有比较$.ajax参数不同的结构,因为$.post是一个简单的快捷方式,而无需指定类型属性,因此$.post$.ajax不能直接互换。

$.post相当于最接近的是:

$.post('ajax_info.json', {}, function(data){ 
    console.log(data); 
}, 'json') 
.error(function(){ 
    // handle erros 
}); 

正如你所看到的,$.post不能设置一个beforeSend处理程序,所以它不是功能与您的$.ajax版本。

0

注意正确的语法jquery.post

jQuery.post(url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ]) 

看到这个http://api.jquery.com/jquery.post/

+0

但我可以按任何顺序传递参数。 –

+0

,因为它无法识别url参数,所以你得到一个net :: ERR_FILE_NOT_FOUND错误 – konghou

0

尝试写你的$。员额方法,如:

$.post("ajax_info.json", function(data) { 
    alert("success"); 
}); 
0

$。员额是$就 的简写,您可以使用它像这样

$("#ajx").click(function(){ 
     $.post("ajax_info.json", function(data) { 
     //success 
      console.log(data); 
     }) 
      .done(function() { 
      alert("second success"); 
      }) 
      .fail(function() { 
      //error handling here 
      alert("error"); 
      }) 
      .always(function() { 
      alert("finished"); 
     }); 
    });