Implement Web Services in PHP & JavaScript.

Implement Web Services in PHP & JavaScript.

本文关键字:amp JavaScript PHP Web Services in Implement      更新时间:2023-09-26

我想将web服务与ajax php和javascript一起使用,我举了这个例子,但我仍然有这个错误。我试了很多代码,请有人帮我。

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>

jsjs.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";}
}
?>

如果您请求的URL与请求源不在同一域上,浏览器安全性将阻止请求完成。这是由于同源政策。

要解决此问题,您需要发出JSONP请求或使用CORS,假设第三方支持它们,或者制作服务器端代理为您发出请求并向该本地URL发出AJAX请求。