Today I saw the first answer on /q/10... that Taobao has an api for mobile phone numbers, so I wrote an html file locally and sent an ajax request to this api. However, it prompted a cross-domain error. No I have dealt with this kind of problem, how to solve it? Please post the code~ Thank you very much, Xiaobai~
迷茫2017-05-19 10:19:45
Cross-domain can be done via JSONP
<script>
$(document).ready(function(){
$("#search").click(function(){
$.ajax({
type: "GET",
url: "http://127.0.0.1:8000/ajaxdemo/serverjsonp.php?number=" + $("#keyword").val(),
dataType: "jsonp",
jsonp: "callback",
success: function(data) {
if (data.success) {
$("#searchResult").html(data.msg);
} else {
$("#searchResult").html("出现错误:" + data.msg);
}
},
error: function(jqXHR){
alert("发生错误:" + jqXHR.status);
},
});
});
$("#save").click(function(){
$.ajax({
type: "POST",
url: "http://127.0.0.1:8000/ajaxdemo/serverjsonp.php",
data: {
name: $("#staffName").val(),
number: $("#staffNumber").val(),
sex: $("#staffSex").val(),
job: $("#staffJob").val()
},
dataType: "json",
success: function(data){
if (data.success) {
$("#createResult").html(data.msg);
} else {
$("#createResult").html("出现错误:" + data.msg);
}
},
error: function(jqXHR){
alert("发生错误:" + jqXHR.status);
},
});
});
});
</script>
This is the test file for applying jsonp cross-domain written before, you can refer to it
PHPz2017-05-19 10:19:45
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>test</title>
</head>
<body>
<input type="text" id="tel">
<input type="button" id="btn" value="submit">
<script src="https://lib.sinaapp.com/js/jquery/3.1.0/jquery-3.1.0.min.js"></script>
<script>
$('#btn').click(function() {
var tel = $('#tel').val().trim();
if (!tel) {
return;
}
$.ajax({
url: 'https://tcc.taobao.com/cc/json/mobile_tel_segment.htm',
dataType: 'jsonp',
data: {
tel: tel
},
})
.done(function(rs) {
console.log(rs);
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
});
</script>
</body>
</html>