0

我正在尝试使用 ajax 将表单提交到不同域上的远程服务器(PHP 服务器)。虽然我听说过使用 jsonp 作为数据类型,但我不确定如何使用它,就像如何从 PHP 服务器返回 jsonp 数据一样。有人可以在这方面为我提供一些帮助吗?如果可以,请指定我应该如何编写返回 jsonp 的 PHP 脚本。

4

2 回答 2

1

我已经通过使用 jsonp 解决了跨域 ajax 请求。我能够通过 GET 而不是 POST 提交表单来做到这一点,所以这取决于您希望表单数据的安全性。我是这样做的:

PHP服务器代码:

header('Access-Control-Allow-Origin: *');
header('content-type: application/json; charset=utf-8');

$first_name = $_GET['first-name'];
$last_name = $_GET['last-name'];

// Process the first-name and last-name here, like storing them in a database or something like that.

$data = array('response' => "success");
echo $_GET['jsonp_callback'].'('.json_encode($data).')';

客户端ajax代码:

function init(){
//allowing cross domain requests :
        $.mobile.allowCrossDomainPages = true;
        $.support.cors = true;

        $.ajax({
                type:"GET",
                url:"http://xyz.com/process.php",
                cache:false,
                data:formData,
                crossDomain: true,
                dataType:'jsonp',
                jsonp:'jsonp_callback',
                 success:function(data){
                    if(data.response=="success"){
                          alert("success");
                    },

                 error:function(){
                    alert('Sorry, unable to register! Try again.');
                }
              });
          }
于 2013-02-02T10:35:56.620 回答
0

这是一个简单的设置:

<?php

 $var1 = $_POST['var1'];
 // repeat mapping form post vars to local php vars

 // code to do something with vars such as INSERT to database goes here

 // select information or build up hard-coded response

 // set header for response
 header('content-type: application/json; charset=utf-8');

 // setup response object
 $data = array('resposne' => 'succcess', 'formId' => 5);

 // return json object
 echo json_encode($data);

?>

那么你的 jQuery 可能看起来像这样:

$.ajax({
  url: 'data.php', 
  data: $('#yourForm').serialize(), 
  success: doSomethingWithResult 
});

function doSomethingWithResponse(result) {
  alert(result.response); // should alert "success"
}

如果这不起作用,网络上还有很多其他更具体的示例。我发现这是一个很好的阅读:http ://www.geekality.net/2010/06/27/php-how-to-easily-provide-json-and-jsonp/

于 2013-02-01T15:37:24.840 回答