2014-04-22 61 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请求。