zoukankan      html  css  js  c++  java
  • 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);
                 })
             }
  • 相关阅读:
    浏览器的跨域请求 与 CORS(跨域资源共享)
    HTML 占位符
    C# 中的 base和this
    推荐一个pdf引擎
    整理wifi相关的知识点
    交叉编译(ISC)DHCP:dhcp-4.3.0b1
    (转载)子网掩码,网关的概念
    海思-VB被占用导致vb无法去初始化
    c++创建文件时重命名同名文件
    iw创建虚拟网卡wlan1,ap_sta共存
  • 原文地址:https://www.cnblogs.com/dybe/p/8253805.html
Copyright © 2011-2022 走看看