有什么区别jQuery $ .get,$ .post& $ .getJSON?

时间:2014-02-13 14:58:02

标签: php jquery json post get

我不确定是否应该使用$.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

2 个答案:

答案 0 :(得分:3)

$.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

答案 1 :(得分:2)

.getJSON()只是.get()的包装。主要区别在于.getJSON() EXPECTS ,即服务器的输出是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
}