我有这样的问题:我的应用程序由 index.html 和一堆其他 html 文件组成,用于我通过 ng-route 导航的应用程序的不同页面。我想将一些数据发布到服务器,但只有在我放入 index.html 时才能做到这一点
这是我的 Angular 代码:
//post data to DB
app.controller('sign_up', function ($scope, $http) {
$scope.check_credentials = function () {
document.getElementById("message").textContent = "";
var request = $http({
method: "post",
url: window.location.href + "php/add_review.php",
headers: { 'Content-Type': 'application/json' },
data: {
review: $scope.review
}
});
request.success(function (data) {
document.getElementById("message").textContent = "You have login successfully with email "+data+request;
});
}
});
我的 PHP 代码:
<?php
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$review = $request->review;
mysql_connect("localhost", "root", "");
mysql_select_db("reherse");
mysql_query("INSERT INTO reviews(review) VALUES('".$review."')");
//echo $request
echo $review;
?>
还有我的 HTML:
<div id="login" ng-controller='sign_up'>
<input type="text" size="40" ng-model="review"><br>
<input type="password" size="40" ng-model="review"><br>
<button ng-click="check_credentials()">Login</button><br>
<span id="message"></span>
</div>
当我在 index.html 上添加此 HTML 时,它成功通过并给我一条消息,其中包含传递到服务器的数据。当此 html 代码添加到其他 html 文件时,它会返回所有 html 页面(给我消息,如您已使用电子邮件成功登录,此处为 html 代码...)。
非常感谢您的帮助!
最佳答案
尝试使用 window.location.origin
而不是 window.location.href
。前者只会为您提供协议(protocol)、主机名和端口(例如 http://localhost:8080
),而后者将为您提供完整的 URL(例如 http://localhost: 8080/somepage.html
)
这就是您的 HTTP 请求在非索引页面上失败的原因,因为它尝试加载的 URL 不正确;它是 http://localhost:8080/somepage.html/php/add_review.php
而不是 http://localhost:8080/php/add_review.php
。它在索引上工作可能是因为您没有指定 index.html
而您只是加载 http://localhost:8080
,在这种情况下 window .location.origin
将等于 window.location.href
(某种程度上,请参见下面的注释)并为您提供正确的 URL。
请注意 window.location.origin
不包含尾部斜线,因此请确保您的 HTTP 请求的 URL 字符串如下所示:
window.location.origin + "/php/add_review.php"
关于javascript - Angular + php 不会从非 index.html 将数据加载到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39090087/