【问题标题】:Send data with ajax, return json用ajax发送数据,返回json
【发布时间】:2015-04-30 17:02:28
【问题描述】:

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

【问题讨论】:

  • 是否返回 json 将取决于服务器端部分,即 getFeed.php ...但是您有一个尾随逗号:timeout: 5000,,这是一个问题。
  • 您的浏览器控制台日志中是否有任何错误?
  • 当我使用echo var_dump($_POST);时收到数组(0)
  • @developerwjk 之后我实际上有一个成功和错误字段,将其删除以使其更清晰,忘记逗号
  • 另外,如果您阅读文档,错误处理程序也不会为 jsonp 触发。您可能不想使用jsonp,因为路径是本地服务器

标签: javascript php jquery ajax json


【解决方案1】:

编辑:事实上,这些键不需要用引号引起来。我在那里弄错了。不过,这似乎仍然是最佳做法,可以避免未来可能出现的问题。

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

【讨论】:

  • 不,实际上我需要像这样使用它:data: {username: usernameVar, userID: userIDVar},
  • 那么它将是"username": usernameVar, "userID": userIDVar。 "username" 和 "userID" 是字符串。
  • 只要属性名称中没有特殊字符,javascript 中的对象键就不需要引号。因此这个答案是无效的
  • @charlietfl 真的吗?我从来不知道这一点。你有没有机会给我一些参考?
  • @charlietfl 刚刚谷歌搜索返回的第一个结果...stackoverflow.com/questions/4201441/… 听起来它不是必需,但最佳实践编辑:它看起来也像 jquery ,从 jquery 1.4 开始,JSON 上需要双引号键,否则它会默默地抛出错误。参考 api.jquery.com/jquery.parsejsonforum.jquery.com/topic/json-on-jquery-1-4
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    好的,首先你的 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'和'another',你会这样:

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

    【讨论】:

    • 不要忘记数据 JSON 中键周围的引号。
    • 数据 JSON 中键周围的引号? o.O
    • 试过了,现在直接进入ajax调用的错误字段
    • 调试,测试它是否到达(或可以找到)php文件(记录它),
    猜你喜欢
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 2021-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多