简体   繁体   English

本地服务器中的Android跨域错误

[英]Android Cross-domain error in local server

I am using phoneGap-2.9.0 我正在使用phoneGap-2.9.0

I can't access my api.php page in local server. 我无法在本地服务器中访问我的api.php页面。 i am getting error! error! alert. 警报。

Please check my code: 请检查我的代码:

Javascript Java脚本

$(document).ready(function () {
    $('#registerForm').submit(function(){ 
        var postData = $(this).serialize();
        var formUrl = $(this).attr('action');
        $.ajax({
            type: 'POST',
            url: formUrl,
            dataType : 'json',
            data: postData,         
            success: function(data){
                alert(data);
            },
            error: function(){
                alert('error!');
            }
        }); 


        return false; 
    }); 
}); 

HTML 的HTML

<form name="registerForm" id="registerForm" method="post" action="http://localhost/android/REST_API/api.php">
        <label>First Name :</label>
        <input type="text" name="first_name" id="first_name" placeholder="First Name" />
        <label>Last Name :</label>
        <input type="text" name="last_name" id="last_name" placeholder="Last Name" />
</form>

api.php api.php

<?php header('Access-Control-Allow-Origin: *'); echo "true"; ?>

Above code i am running in browser it working fine. 上面的代码我在浏览器中运行它工作正常。 But it is not working in device emulator. 但是它不能在设备仿真器中工作。 In emulator if i am using http://www.raddyx.in/api.php instead of http://localhost/android/REST_API/api.php i am gettng true . 在模拟器中,如果我使用的是http://www.raddyx.in/api.php而不是http://localhost/android/REST_API/api.php我为true

Please me and let me know the problem. 请我让我知道问题所在。

Screenshot: 屏幕截图:

在此处输入图片说明

I'm not 100% sure why this is happening but my money is on the fact that its an emulator, if you deploy it to a physical device it should work the same as in a desktop browser, If you try JSONP instead of JSON then your issue should be resolved on the emulator as this sidesteps any cross domain security breach the emulator may think is happening. 我不是100%知道为什么会这样,但是我的钱是因为它是一个仿真器,如果将其部署到物理设备上,它的工作原理应与台式机浏览器中的工作原理相同,如果尝试使用JSONP而不是JSON,您的问题应在模拟器上解决,因为这可以避免模拟器可能认为正在发生的任何跨域安全漏洞。

$(document).ready(function () {
$('#registerForm').submit(function(){ 
    var postData = $(this).serialize();
    var formUrl = $(this).attr('action');
    $.ajax({
        type: 'POST',
        url: formUrl,
        dataType : 'jsonp',
        data: postData,         
        success: function(data){
            alert(data);
        },
        error: function(){
            alert('error!');
        }
    }); 


    return false; 
}); 
}); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM