douduoting8408 2013-01-27 07:28
浏览 263
已采纳

跨域请求,但POST为空

I need to implement a cross-domain POST request. Using this code, everything worked fine in the same domain. But when I moved the backend to another domain - all stopped working! Therefore, there can be typos. There can be only where the error is related to the cross-domain request. I try send POST request using ajax and JSONP:

function requestToServer(url, success, myObjects) 
{
    $.ajax({
        type: "POST",
        crossDomain: true,
        dataType: 'jsonp',
        jsonp: 'jsonp_callback',
        url: url,
        data: "arrObjects=" + JSON.stringify(myObjects),
        success: function(data)
        {
            success(data);
        },
        error: function()
        {
            alert('Server connection error!!!');
        }
    });
}

and server-script, where send data:

<?php

header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']);
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type');

include 'connection.php';

$arrObjects = json_decode($_POST['arrObjects']);


$title = $arrObjects->title;
$msg = $arrObjects->msg;
$lat = $arrObjects->lat;
$lon = $arrObjects->lon;

$query = "INSERT INTO `geo_markers` (`id`, `title`, `description`, `lat`, `lon`) 
VALUES (NULL, '{$title}', '{$msg}', '{$lat}', '{$lon}')";

$res = mysqlQuery($query);

echo $_GET['jsonp_callback'].'({"success":true});';

mysql_close();
?>

but $_POST is empty. But $_GET takes values $_POST. If I check $_POST using var_dump, it is array(0), $_GET contains all send data!

What's wrong here? What went wrong can it be?

  • 写回答

3条回答 默认 最新

  • dqwh0108 2013-01-27 07:37
    关注

    You have send JSON formatted since you are using jsonp format. try json_encode before you echo data.

    Also keep in mind that when you make a cross domain jsonp call, JSONP isn't AJAX, it's merely a dynamic script element. You can't do a POST with a dynamic script element. There's no place to put the POST data. So You will have to use GET method.

    Also keep in mind that you can use below format

    $.getJSON(url + "?callback=?", null, function(data) {
    
    });
    

    Read more

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型