django 筆記15 ajax系列

參考 http://www.cnblogs.com/wupeiqi/articles/5703697.html
# 原生操做
# jQuery操做
# 僞Ajax操做
# XMLHttpReques
僞ajax操做

<iframe src='http://www.baidu.com'><iframe>  頁面嵌套

僞造一個ajax請求發日後臺 頁面不刷新
iframe標籤 和 form表單  target  iframe name

<form action = "/ajax_json/" method = "POST" target = 'ifm1'>
    <iframe id = 'ifm1' name = 'ifm1' ></iframe>
    <input type = 'text' name = "username" />
    <input type = 'text' name = 'email' />
    <input type = 'submit' onclick="submitForm()" value = "提交"/>
</form>
<script>
    function submitForm(){
        $('#ifm1').load(function(){
            #在 iframe裏找 返回的內容
            var text = $('#ifm1').contents().find('body').text();
            var obj = JSON.parse(text);

        })
    }
<script>

Ajax 原生的 jQuery 和iframe 三種
時機:
    若是發送的是普通的數據 首先用jQuery 接着XMLHttpRequest,最後再考慮iframe
    若是發送的是不普通數據(文件)
原生ajax操做
function getXHR(){
    var xhr = null;
    if(XMLHttpRequest){
        xhr = new XMLHttpRequest();
    }else{
        xhr = new ActiveXobject('Microsoft.XMLHTTP');
    }
    return xhr;
}

function Ajax1(){
    var xhr = getXHR();
    xhr.open('POST', '/ajax_json/', true);
    xhr.onreadystatechange = function(){
        if(xhr.readyState == 4){
        //接收完畢後
        var obj = JSON.parse(xhr.responseText);
        console.log(obj)
        }
    };
    xhr.setRequestHeader('k1', 'v1');
    xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset-UTF-8');
    xhr.send('name=root; pwd=123')
}
相關文章
相關標籤/搜索