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 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败