【问题标题】:What is the difference between jQuery $.get, $.post & $.getJSON?jQuery $.get、$.post 和 $.getJSON 有什么区别?
【发布时间】:2014-02-13 14:58:01
【问题描述】:

我不确定我应该使用$.get 还是$.getJSON. 在这个例子中我应该使用哪一个?

我的代码:

if (isset($_GET['numberofwelds']) && isset($_GET['numberofconwelds']))
{
    // Now we know both values definitely exist, VALIDATE them
    $numwelds = $_GET['numberofwelds'];
    $numconwelds = $_GET['numberofconwelds'];

    if (is_int($numwelds) && is_int($numconwelds))
    {
        // Calculate your total
        $total = $numwelds + $numconwelds;
        echo json_encode($total);


    }
    else

【问题讨论】:

  • “get、post 或 JSON”就像问“苹果、香蕉还是飞机”。您无法比较 JSON(一种用于序列化分层数据的格式)和 GET/POST(两种发出 HTTP 请求的方法)。
  • 文档中解释了差异。比较this 的第一段和this 的第一段。
  • 同样看紧跟在这句话后面的代码:“This is a shorthand Ajax function, which is equivalent to”
  • @meagar 他在谈论 jquery 方法。我已经更新了标题。
  • 另外,GET 和 POST 实际上只是将数据发送到 Web 服务器的两种不同方式。 GET 用于只检索数据而不更改数据的查询,例如“我想要google.com 的网页”,或“给我数据库中与该搜索词匹配的所有条目”。 POST 用于将数据上传到服务器的查询,例如“我对这篇文章发表了评论;这是我的姓名和评论文本”。 Web 服务器可以随意忽略这种模式,但它们不应该。

标签: php jquery json post get


【解决方案1】:

$.getJson()$.get()$.post 只是具有不同参数的 $.ajax() 方法的别名。

$.get() 使用 HTTP GET 请求从服务器加载数据。 $.ajax() 等效:

$.ajax({
     url: url,
     data: data,
     success: success,
     dataType: dataType
});

$.post() 使用 HTTP POST 请求从服务器加载数据。 $.ajax() 等效:

$.ajax({
     type: "POST",
     url: url,
     data: data,
     success: success,
     dataType: dataType
});

$.getJSON() 使用 GET HTTP 请求从服务器加载 JSON 编码的数据。 $.ajax() 等效:

$.ajax({
  dataType: "json",
  url: url,
    data: data,
    success: success
});

UPD:

根据您的代码,您应该使用$.getJSON。因为两点:

  1. 由于您正在查看 $_GET 变量,因此您需要 HTTP GET 请求
  2. 由于您要从服务器返回 JSON,您需要将 dataType 设置为 JSON

【讨论】:

    【解决方案2】:

    .getJSON() 只是.get() 的包装。主要区别在于.getJSON() 期望 服务器的输出是一个 json 字符串。 .get() 不在乎它得到了什么。

    基本上 .getjSON 是

    function .getJSON(a,b,c) {
        $.get(a,b,c,'json');
                    ^^^^^^--- 4th param of .get tells jquery what data type you're expecting
    }
    

    【讨论】:

      猜你喜欢
      • 2015-08-03
      • 2011-03-05
      • 2011-03-29
      • 2013-07-02
      • 2011-05-07
      • 1970-01-01
      • 2011-06-07
      • 2013-08-26
      • 1970-01-01
      相关资源
      最近更新 更多