ajax 请求常用写法

一、jquery.ajax()

function checkSubmit()
    {
        var formData = new FormData($('#ImportForm')[0]);//Form表单数据
        url = '@Url.Action("ImportQuestionExcel","Common")' + "?time=" + new Date();
        console.log(url);
        $.ajax({
            type:"POST",
            url:url,
            data: formData,
            processData: false,//不处理数据
            contentType: false,//不定义类型 因为上传了文件
            success:function(data){
                Import_OnSuccess(data);
            },
            error:function(){
                $(document).alertmsg('confirm',"处理异常");
            }
        });
    }
View Code

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript">
        var xmlhttp = createXHR();
        function createXHR() {
            var xhr;
            if (window.XMLHttpRequest) {
                xhr = new XMLHttpRequest();
            } else {
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            }
            return xhr;
        }

        function login() {
            var span = document.getElementById("msg");
            span.innerHTML = "正在登录...";

            var name = document.getElementById("txtName").value;
            var pwd = document.getElementById("txtPwd").value;
            var postData = "n=" + name + "&p=" + pwd;

            xmlhttp.open("post", "02-post.ashx", true);
            //!!!!!!!!!!!!!!!!!!!post请求,必须设置Content-Type
            xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

            xmlhttp.onreadystatechange = function () {
                if (xmlhttp.readyState == 4) {
                    if (xmlhttp.status == 200) {
                        var r = xmlhttp.responseText;
                        
                        if (r == 1) {
                            span.innerHTML = "登录成功";
                        } else if (r == 0) {
                            span.innerHTML = "登录失败";
                        } else {
                            span.innerHTML = "未知错误";
                        }
                    }
                    else {
                        span.innerHTML = "服务器内部错误";
                    }
                }
            }
            xmlhttp.send(postData);
        }
    </script>
</head>
<body>
    用户名:<input type="text" id="txtName" /><br />
    密码:<input type="text" id="txtPwd" /><br />
    <input type="button" id="btnLogin" value="Login" onclick="login()" /><span style="color:Red" id="msg"></span>
</body>
</html>

posted on 2013-12-12 13:17  月&&生  阅读(558)  评论(0编辑  收藏  举报