2016-08-22 106 views
2

我有这样的问题:我的应用程序由index.html和其他一些html文件组成,这些html文件用于通过ng-route导航的应用程序的不同页面。我想发布一些数据到服务器,但我能做到这一点只有当我穿上的index.htmlAngular + php不会从index.html加载数据到服务器

这里是我的角度代码:

//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代码...)。

会非常感激的帮助!

回答

0

尝试使用window.location.origin而不是window.location.href。前者会给你刚才的协议,主机名和端口(例如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"

+0

谢谢SOOOO了!它正在工作! –

+0

@ManavalanMavan,你会介意将此标记为接受的答案吗? –

相关问题