JSON跨域与PHP文件和本地javascript文件的通信 [英] JSON crossdomain communication with PHP file and a local javascript file

查看:69
本文介绍了JSON跨域与PHP文件和本地javascript文件的通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JSON新手,但在PHP和javascript方面有很好的经验。问题很简单,答案可能更简单。我无法将数据从服务器上的PHP文件发送到我本地的另一个PHP文件,该文件将从服务器接收JSON格式的数据。我做错了什么?

I am a JSON newbie, but have good experience in PHP and javascript. The question is simple, and the answer might be simpler. I am having trouble sending data from the PHP file on the server, to another PHP file that I have locally which would receive the data in JSON format from the server. What am I doing wrong?

Javascript Frag(本地)

$(document).ready(function(){
//attach a jQuery live event to the button
$.getJSON('http://www.xpal.com/ws_users.php?action=get_user_data&user_id=33',function(data) {

        alert(data); //uncomment this for debug
        $('#showdata').html("<p>Username= "+data.username+"<br> Email= "+data.email+"<br> Firstname="+data.firstname+"<br> Lastname="+data.lastname+"</p>");
    });

});

PHP Frag(Server @ xpal.com):

$ users =新用户;

$users=new users;

if($_GET['action']=="get_user_data")
{
$user_id=$_GET['user_id'];
$assoc=array(
                "username"=>$users->return_username($user_id),
                "email"=>$users->return_user_emailid($user_id),
                "firstname"=>$users->return_user_firstname($user_id),
                "lastname"=>$users->return_user_lastname($user_id)
            );
echo json_encode($assoc);
}   

编辑:

错误消息:XMLHttpRequest无法加载xpal.com/ws_users.php?action=get_user_data&user_id=33。 Access-Control-Allow-Origin不允许使用origin localhost。

The error message : XMLHttpRequest cannot load xpal.com/ws_users.php?action=get_user_data&user_id=33. Origin localhost is not allowed by Access-Control-Allow-Origin.

推荐答案

要使用jsonp,如其他建议,您必须要么把回调=?在您的URL的末尾,或使用$ .ajax()并指定dataType是jsonp。示例这里

To use jsonp, as other suggest, you must either put "callback=?" at the end of your URL, or use $.ajax() and specify the dataType is jsonp. Examples here.

这篇关于JSON跨域与PHP文件和本地javascript文件的通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆