gpt4 book ai didi

php - 使用 Angular.js 的 HTTP POST

转载 作者:IT王子 更新时间:2023-10-28 23:58:59 24 4
gpt4 key购买 nike

我是新手,我想使用 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 data1 将返回如下内容:{ "code" : 1 }

我无权访问脚本或托管它们的服务器。

我想知道 Angular.js 是否有可能读取 JSON data1,将该 data1 与它们在我的 JSON data2 中定义的内容相匹配,然后将它们输出到我的 View ( <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;
};
}

尽管它正在处理 HTTP/1.1 200,但到目前为止它向 View 发布的所有内容都是“请求失败”哈哈。我知道我还有很长的路要走,但我将不胜感激任何帮助。一旦我弄清楚如何将正确的 JSON data1 发布到 View ,下一步就是匹配并输出适当的 data2。提前致谢!

最佳答案

实际上问题出在 PHP 的后端,您没有像往常一样检索发布的数据,这对我有用:

function PhpCtrl($scope, $http, $templateCache) {
var method = 'POST';
var url = 'url.php';
$scope.codeStatus = "";
$scope.add = function() {
var FormData = {
'name' : document.f1.name.value,
'password' : document.f1.password.value
};
$http({
method: method,
url: url,
data: FormData,
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;
};
}

在 PHP 文件中:

$data = json_decode(file_get_contents("php://input"));
echo $data->name;

希望这对您有所帮助。

关于php - 使用 Angular.js 的 HTTP POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15707431/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com