使用ajax发送数据,返回json

时间:2015-02-27 21:09:02

标签: javascript php jquery ajax json

我想发送一个字符串并返回json。

这样可行,但它不会返回json代码

$.ajax({
    url: "getFeed.php",
    type: "post",
    data: myString
});

当我希望它返回一个json字符串时,它会给我一个错误。

$.ajax({
    url: 'getFeed.php',
    type: "post",
    data: {string1: "testdata", string2: "testdata"},
    dataType: 'jsonp',
    jsonp: 'jsoncallback',
    timeout: 5000,
});

由于某种原因,服务器没有收到任何数据。

我该怎么写这个? (我想发送2个字符串)

3 个答案:

答案 0 :(得分:1)

JSONP不允许使用POST方法,因为它实际上只是一个脚本请求。

由于使用的路径是相对的(同一域),我建议您使用json数据类型,因为jsonp用于跨域请求。

答案 1 :(得分:0)

编辑:事实上,密钥不需要在引号中。我错了。但是,为了避免潜在的未来问题,它似乎仍然是最佳做法。

$.ajax({
    "url": "getFeed.php",
    "type": "post",
    "data": {"string1": "testdata", "string2": "testdata"},
    "dataType": "jsonp",
    "jsonp": "jsoncallback",
    "timeout": 5000,
});

答案 2 :(得分:0)

好的,首先你的ajax语法似乎不对。

假设您要发送两个字符串stringAstringB。你的php文件是getFeed.php

你的ajax看起来像这样:

    $.ajax({
               type : "POST",
               url : "getFeed.php",
               data : {firstVar:stringA,secondVar:stringB},
               dataType: "json",
               success : function(data){

                         // Here you receive the JSON decoded.
                        var mesage = data.msg;
                 }  
        });

getFeed.php内,你会收到这样的字符串:

$firstString = $_POST['firstVar'];
$secondString = $_POST['secondVar'];

当您将JSON对象从getFeed.php返回到ajax时,您就会这样做:

$myArray = array("msg"=>"Hello World", "another"=>"thing");
echo json_encode($myArray);

让我们回到ajax函数,成功部分是,你收到一个参数data,如果你想访问“消息”,那么和另一个',你会这样:

       success : function(data){

                         var first = data.msg;
                         var second = data.another;
               }  
相关问题