我是新手,想使用Angular.js进行HTTP POST请求。我要访问一些参数仅为POST变量的PHP脚本。每个脚本返回一个JSON字符串。通常在HTML表单中,可以这样发出请求:
<form method="post" action="url.php">
<input name="this">
<input name="that">
<input value="Submit">
</form>
根据您的输入并在单击提交后,JSON数据1将返回类似于此的内容:{ "code" : 1 }
。我无法访问脚本或托管它们的服务器。
我想知道Angular.js是否能够读取JSON数据1,将其与我的JSON数据2中定义的数据进行匹配,然后将它们输出到我的视图(
<pre>data2</pre>
)。例如,如果检索到
{ "code" : 1 }
,我希望我的JSON输出代码#1的值:{ "code" : [
{ 1: "User already logged in." },
{ 2: "Wrong parameters, try again."},
{ 3: "etc., etc." }
]
};
这是我的尝试:
<form ng-controller="PhpCtrl" name="f1">
<input type="text" name="name">
<input type="text" name="password">
<pre ng-model="codeStatus">{{codeStatus}}</pre>
<input type="submit" ng-click="add()" value="Submit">
</form>
function PhpCtrl($scope, $http, $templateCache) {
$scope.method = 'POST';
$scope.url = 'url.php';
$scope.codeStatus = "";
$scope.add = function() {
$http({
method: $scope.method,
url: $scope.url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
cache: $templateCache
}).
success(function(response) {
$scope.codeStatus = response.data;
}).
error(function(response) {
$scope.codeStatus = response || "Request failed";
});
return false;
};
}
到目前为止,它只向视图(post to the view)发布了“请求失败(Request failed)”的信息,虽然它正在处理HTTP/1.1 200。我知道我还有很长的路要走,但我会感激任何帮助。一旦我弄清楚如何向视图(post to the view)发布正确的JSON数据1,下一步就是匹配和输出相应的数据2。提前致谢!
data: FormData
作为$http请求的参数,然后发送请求,或者是因为headers不正确。希望这可以帮助到你。 - Yahya KACEM