ajax請求學習之 之使用jsonp來處理跨域

使用jsonp來處理跨域php

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Demo</title>
<style>
body, input, select, button, h1 {
    font-size: 28px;
    line-height:1.7;
}
</style>    
</head>

<body>

<h1>員工查詢</h1>

<label>請輸入員工編號:</label>
<input type="text" id="keyword" />
<button id="search">查詢</button>
<p id="searchResult"></p>

<h1>員工新建</h1>
<label>請輸入員工姓名:</label>
<input type="text" id="staffName" /><br>
<label>請輸入員工編號:</label>
<input type="text" id="staffNumber" /><br>
<label>請選擇員工性別:</label>
<select id="staffSex">
<option>女</option>
<option>男</option>
</select><br>
<label>請輸入員工職位:</label>
<input type="text" id="staffJob" /><br>
<button id="save">保存</button>
<p id="createResult"></p>

<script src="http://apps.bdimg.com/libs/jquery/1.11.1/jquery.js"></script>
<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>
</body>
</html>
相關文章
相關標籤/搜索