【jQuery、Express.js】AJAX提交Form

HTML/CSS代码

构建onclick事件

<div class = "row">
<div class = "col-md-10">
<input type="text" id="inputcpn" class="form-control" name="inputcpn">
</div>
<div class = "col-md-2">
<button type = "button" class="btn btn-green" onclick="nanshou()">Apply</button>
</div>
</div>

JavaScript代码(jQuery)

TYPE:请求类型,

URL:发送请求的地址,

DATA:发送到服务器的数据,

DATATYPE:预期服务器返回的数据类型,可以为xml、html、json、javascript、text等。

SUCCESS:请求成功后的回调函数。

进行AJAX请求,其中值得注意的地方是若数据格式为JSON,那么value属性必须为已经定义过的变量或者值(如果值为字符串,则使用双引号,JSON不支持单引号)。

<script language="javascript" type="text/javascript">
    function nanshou(){
        var cpn= $('#inputcpn').val();
        var str= "" ;
        $('.productid').each(function(){
            str += $(this).html();
            str += ",";
        });
        str = str.substring(0, str.length - 1);
        var storeid= $('#currentstoreid').html();
        params = {inputcpn: cpn, products: str, storeid: storeid};

        $.ajax({
                type : "POST",
                url : "/product/applycoupons",
                data : params,
                dataType:'json',
                success:function(data)
                {
                    if(data.result == "fail"){
                        window.location="/product/checkout/cart/"+storeid+"/Invalid";
                    }
                    else{
                        window.location="/product/checkout/cart/"+storeid+"/Applied";

                    }
                }
            });

    }
</script>

Express.js 代码(在route products.js 文件)

顺手写(编)了一个简单逻辑的回传给AJAX的if语句。

var express  = require('express');

var app = express.Router();

app.post(['/applycoupons'], function(req, res){
var products = req.body.products; var storeid = req.body.storeid; var code = req.body.inputcpn;
  if (code == "") {
  res.json({'result': 'fail'});
  res.end();
  return false;
  }
else{
    res.json({'result': 'fail'});   
    res.end();
    return false;
}
});

猜你喜欢

转载自www.cnblogs.com/yidansheng/p/9384173.html