2017-07-27 76 views
0

所以我使用查询字符串将数据从窗体传递到我的服务器。查询字符串是这样的:将数据传递给服务器的更好方法?

this.$http.post('http://localhost:3000/operation?Stime='+this.Stime+'&Etime='+this.Etime+'&eAMPM='+this.eAMPM+'&sAMPM='+this.sAMPM+'&id='+this.id+'&activity='+this.activity+'&auto_insert='+this.auto_insert+'&yearmonthday='+this.yearmonthday+'&color1='+this.c) 

,并在我的服务器我有所有这些变量来存储查询的变量:

var color = req.query.color1; 
var Stime = req.query.Stime; 
var Etime = req.query.Etime; 
var sAMPM = req.query.sAMPM; 
var eAMPM = req.query.eAMPM; 
var id = req.query.id; 
var activity = req.query.activity; 
var requestAccepted = req.query.requestAccepted; 
var yearmonthday = req.query.yearmonthday; 
var auto_insert = req.query.auto_insert; 

这似乎只是一个大量的代码只是张贴我的变量服务器(它工作得很好),但我想知道是否有一些方法可以重构它/使它更清洁

+0

是它的角HTTP模块?然后使用data属性将数据作为JSON对象发送。 –

+1

JSON是您的朋友。它将作为请求的有效载荷。您仍然可以保留一些查询字符串以进行路由。我没有回答这个问题,因为我现在很匆忙,但我非常肯定这是最好的方法:https://stackoverflow.com/questions/10955017/sending-json-to-php-使用-ajax – Loudenvier

+0

好......我不完全确定你为什么要在服务器上创建查询成员的本地副本。不过,你在客户端使用哪个库/框架?例如,在angular或jquery中,您通常必须使用提供的API配置您的请求,而不是手动组合url。 –

回答

0

当然有!

考虑做一些研究到HTTP消息体:

消息正文是携带来自服务器的实际的HTTP请求数据(包括表格数据和上载的,等)和HTTP响应数据的一个(包括文件,图像等)。


在你的情况,你可以改变你的角度$ HTTP POST请求如下 -

var data = { 
    Stime: '+this.Stime+', 
    Etime: '+this.Etime+', 
    eAMPM: '+this.eAMPM+', 
    sAMPM: '+this.sAMPM+', 
    id: '+this.id+', 
    activity: '+this.activity+', 
    auto_insert: '+this.auto_insert+', 
    yearmonthday: '+this.yearmonthday+', 
    color1: '+this.c+' 
} 

$http({ 
    method: 'POST', 
    url: 'http://localhost:3000/operation', 
    data: JSON.stringify(data) 
}) 
+0

如果使用angular 1.x,则可能更希望使用[resources](https://docs.angularjs.org/api/ngResource/service/$resource) –

相关问题