如何在没有jQuery的情况下使用$ http发布urlencoded表单数据? [英] How do I POST urlencoded form data with $http without jQuery?

查看:306
本文介绍了如何在没有jQuery的情况下使用$ http发布urlencoded表单数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是AngularJS的新手,一开始,我想只使用AngularJS开发一个新的应用程序。

I am new to AngularJS, and for a start, I thought to develop a new application using only AngularJS.

我正在尝试对其进行AJAX调用服务器端,从我的Angular App使用 $ http

I am trying to make an AJAX call to the server side, using $http from my Angular App.

为了发送参数,我尝试了以下方法: / p>

For sending the parameters, I tried the following:

$http({
    method: "post",
    url: URL,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    data: $.param({username: $scope.userName, password: $scope.password})
}).success(function(result){
    console.log(result);
});

这是有效的,但它也在 $。param中使用jQuery 。为了消除对jQuery的依赖,我尝试了:

This is working, but it is using jQuery as well at $.param. For removing the dependency on jQuery, I tried:

data: {username: $scope.userName, password: $scope.password}

但这似乎失败了。然后我尝试 params

but this seemed to fail. Then I tried params:

params: {username: $scope.userName, password: $scope.password}

但这似乎也失败了。然后我尝试了 JSON.stringify

but this also seemed to fail. Then I tried JSON.stringify:

data: JSON.stringify({username: $scope.userName, password: $scope.password})

我找到了这些可能的答案我的追求,但没有成功。难道我做错了什么?我确信,AngularJS会提供这个功能,但是如何?

I found these possible answers to my quest, but was unsuccessful. Am I doing something wrong? I am sure, AngularJS would provide this functionality, but how?

推荐答案

我认为你需要做的是转换你的数据对象不是JSON字符串,而是url params。

I think you need to do is to transform your data from object not to JSON string, but to url params.

来自Ben Nadel的博客


默认情况下,$ http服务将转发请求
将数据序列化为JSON,然后使用content-
类型application / json发布。当我们想要将值作为FORM
帖子发布时,我们需要更改序列化算法并使用内容类型application / x-www-form-urlencoded发布数据
。 / p>

By default, the $http service will transform the outgoing request by serializing the data as JSON and then posting it with the content- type, "application/json". When we want to post the value as a FORM post, we need to change the serialization algorithm and post the data with the content-type, "application/x-www-form-urlencoded".

示例从此处

$http({
    method: 'POST',
    url: url,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    transformRequest: function(obj) {
        var str = [];
        for(var p in obj)
        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
        return str.join("&");
    },
    data: {username: $scope.userName, password: $scope.password}
}).then(function () {});



更新



添加新服务使用AngularJS V1.4,参见

UPDATE

To use new services added with AngularJS V1.4, see

  • URL-encoding variables using only AngularJS services

这篇关于如何在没有jQuery的情况下使用$ http发布urlencoded表单数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆