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

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

问题描述

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

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

我正在尝试使用 Angular 应用程序中的 $http 对服务器端进行 AJAX 调用.

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

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

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 参数.

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,然后将其与内容一起发布-类型,应用程序/json".当我们想将值作为 FORM 发布时post,我们需要改变序列化算法和post数据内容类型为application/x-www-form-urlencoded".

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

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

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