nodejs:ajax post與get的區別,getjson的使用


一,get方法是nodejs用來接收數據常用的方法,通過url傳遞

參數可以在地址看到(登陸的時候不安全),並且由於地址欄對參數長度的控制,因此get方法不能做大數據的提交

在頁面發送數據

 $.get("../action/zxly.js", {nc: nc, qq: qq, em: em, zt: zt, nr: nr}, function (result) {
                        console.log(result.args);
                        if (result.args=="ok") {   //接收js返回的數據
                            alert("留言成功!")
                        }
                    })

在js中接收數據

 router.get("/action/zxly.js?",function(req,res) {

            //req.query:獲取URL的查詢參數串
            var par=req.query;
             res.send({"args":result}); //向頁面發送數據    
})        

二,post方法通過body來獲得參數需要 加載相應的模塊

安裝命令:

npm install body-parser

在app.js中添加相應的模塊

var bodyParser = require('body-parser');//加載此模塊在body中去獲取參數
app.use(bodyParser.urlencoded({extended:false}));//參數方式是字符串

表單提交:

<form action="<%=basePath%>action/tedst.js"    method="post">
                   用戶名:<input type="text" name="username" />
                   <br/>
                   密碼:<input type="password" name="pwd"/><br/>
                        <input type="submit"  value="提交"/>
            </form>

 js接收:

如果做參數的安全提交例如用戶名,或者大量的數據提交就需要用到post方法
          post方法只能表單提交,不能通過地址欄訪問。

router.post("/action/tedst.js",function(req,res,next)
res.send("----post提交成功"+req.body.username+" "+ req.body.pwd); next(); })

三,getjson跨域接收請求

js中返回數據:

router.get("/action/Testgetjson",function(req,res,next){
             var m=req.query.jsoncallback;
               res.write(m+"({\"key\":\"abcdef\"})");//跨域返回的數據格式
              // res.write("{\"key\":\"abcdef\"}");    //同域返回數據的格式
              res.end();
        })

 頁面中發送請求並接收返回的參數

function test(){
             $.getJSON("http://localhost:3001/action/Testgetjson?jsoncallback=?", function(data){
                   $("span").text(data.key);
             })
         }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM