Home  >  Article  >  Web Front-end  >  Make a cross-domain ajax request test through jquery's $.getJSON_jquery

Make a cross-domain ajax request test through jquery's $.getJSON_jquery

WBOY
WBOYOriginal
2016-05-16 18:07:15972browse

(Mainly just keep it as a backup. I am afraid that I will use it in the future but forget it, so there is not much explanation. If you really can’t understand it, you can try it according to my code.)
My backend is using PHP, one of the main functions of the following code is to provide an appointment registration interface. The data that needs to be passed in are: user name, contact number and address
/*appointment registration execution interface*/

Copy code The code is as follows:

/*Reservation registration execution interface*/
case "yuyue_interface":
$name = trim($_GET['name']);
$phone = trim($_GET['phone']);
$addr = trim($_GET['addr']);
$dt = date("Y-m-d H:i:s");
$cb = $_GET['callback'];
if($name == "" || $name == NULL) {
echo $cb."({code:".json_encode(1)."})";
}elseif($phone == "" || $phone == NULL){
echo $cb."({code:".json_encode(2)."})";
}elseif($addr == "" || $addr == NULL){
echo $cb."( {code:".json_encode(3)."})";
}else{
$db->execute("insert into tb_yuyue (realname,telphone,danwei,dt,ischeck) values ​​('$ name','$phone','$addr','$dt',0)");
echo $cb."({code:".json_encode(0)."})";
}
exit;
break;

Then the front-end processing
Copy code The code is as follows:

$(document).ready(function(){
//The following 3 parameters are required for appointment registration
var name = "name"; / /varchar type, the length is up to 8 digits (4 Chinese characters)
var phone = "phone"; //varchar type, the length is 11 digits
var addr = "addr"; //varchar type, the length is up to 11 digits It is 500 digits (250 Chinese characters)
$.getJSON("http://request website address/data.php?ac=yuyue_interface&name=" name "&phone=" phone "&addr=" addr "&callback=?", function(data){
if(data.code==1){
//Custom code
alert("Name cannot be empty");
}else if(data.code= =2){
//Custom code
alert("Mobile phone cannot be empty");
}else if(data.code==3){
//Custom code
alert("The unit cannot be empty");
}else{
//Custom code
alert("Reservation successful");
}
});
});

It should be noted that in the back-end php code, the " &callback=? " passed in must also be output, such as:
Copy code The code is as follows:

$cb = $_GET['callback'];
echo $cb."({code :".json_encode(4)."})";

The above is a simple $.getJSON test. Through this test, we can learn how to use $.getJSON and also learn How to make an interface to allow others to make cross-domain requests.
If you have any questions, you can ask them below. If I made a mistake, please point it out for me.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn