使用ajax发送数据,返回json

Send data with ajax, return json

本文关键字:返回 json 数据 ajax 使用      更新时间:2024-06-22

我想发送一个字符串并返回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个字符串)

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

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

好的,首先您的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,如果您想访问"msg"answers"other",您会希望这样:

       success : function(data){
                         var first = data.msg;
                         var second = data.another;
               }  

EDIT:键实际上不需要用引号括起来。我错了。然而,这似乎仍然是避免未来潜在问题的最佳做法。

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