我正在尝试使用ajax将表单提交到不同域上的远程服务器(PHP服务器)。虽然我听说过使用jsonp作为数据类型,但我不确定如何使用它,就像如何从PHP服务器返回jsonp数据一样。有人能在这方面给我一些帮助吗?如果可以,请指定我应该如何编写返回jsonp的PHP脚本。
发布于 2013-02-02 18:35:57
我已经使用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-01 23:37:25
下面是一个简单的设置:
<?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/
https://stackoverflow.com/questions/14645930
复制相似问题