2014-04-22 105 views
-1

我想用ajax php和javacript的web服務,這個例子,但我仍然有這個錯誤。 我試了很多代碼,請別人幫我。在PHP和JavaScript中實現Web服務。

XMLHttpRequest無法加載xxxxx/login.php。請求的資源上沒有「Access-Control-Allow-Origin」標題。因此不允許原產地'null'訪問。 index.html的:1周

的index.html

<html><head> 
<script src="jquery-2.1.0.js"></script> 
<script src="jsjsjs.js"></script> 
</head> 
<body> 
<div id='logindiv'>  
     <label>Username:</label> 
      <input name="username" id="username" type="text"> 
     <label>Password:</label> 
      <input name="password" id="password" type="password"> 
      <input value="Submit" name="submit" class="submit" type="submit" onclick='chk_ajax_login_with_php();'> 
     <div id='status'></div> 
</div> 
</body> 
</html> 

jsjsjs.js

function chk_ajax_login_with_php(){ 
    var username=document.getElementById("username").value; 
    var password=document.getElementById("password").value; 
    var params = "username="+username+"&password="+password; 
      var url = "xxxxx/login.php"; 
       $.ajax({ 
           type: 'POST', 
           url: url, 
           dataType: 'html', 
           data: params, 
           beforeSend: function() { 
           document.getElementById("status").innerHTML= 'checking...' ;}, 
           complete: function() { }, 
           success: function(html) { 
            document.getElementById("status").innerHTML= html; 
            if(html=="success"){          
             window.location ="/test.php"          
            }          
           } 
         });  
} 

的login.php

<?php 
if ($_POST['username'] != null and $_POST['username'] != "" and $_POST['password'] != null and $_POST['password'] != ""){ 
$username = $_POST['username']; 
$password = $_POST['password']; 
} 
if($username == "youssef" and $password=="4656"){ 
echo "Nice"; 
} 
else { echo "nono";} 
} 
?> 
+0

在請求的資源上存在[No'Access-Control-Allow-Origin'標頭可能存在重複。'爲什麼當我使用POSTMAN時沒有顯示?](http://stackoverflow.com/questions/20035101/no-access-control-allow-origin-header-is-present-on-the-requested-resource-w) – Quentin

+0

您應該[瞭解如何正確使用標籤元素](http://www.456bereastreet.com/archive/200711/use_the_label_element_to_make_your_html_forms_accessible/)。如果沒有for屬性或者表單控件,標籤就沒用了。 – Quentin

回答

0

如果您是從請求URL不上與請求相同的域產生瀏覽器安全性將阻止請求完成。這是由於Same Origin Policy

要解決此問題,您需要製作JSONP請求或使用CORS,假設第三方支持它們,或者使服務器端代理爲您提出請求並向此本地URL發出AJAX請求。