发送和检索php和jquery ajax之间的键值对?

时间:2009-12-06 04:28:38

标签: php jquery ajax

我使用$ .get来运行php文件。如何从php文件向jquery发送键值对(例如变量)?当发送时,我如何用jquery检索它们?我想验证例如。在jquery中if(key == value)。

$ .getJSON和$ .get之间有什么区别?如果我想运行php我不能使用$ .getJSON?

我尝试在php文件中使用:

     echo '{"url": 1}';

我也试过了:

    $json['url'] = 2;
    echo json_encode($json);

在jquery文件中我使用:

     alert(data.url);

但它没有用。它显示“未定义”。

出了什么问题

2 个答案:

答案 0 :(得分:3)

您可以将$.getJSON()与PHP一起使用。使用Javascript:

$(function() {
  $.getJSON("/some/script.php", function(data) {
    alert(data.url);
  });
});

在PHP方面使用json_encode()

<?php
header("Content-Type: application/json");
$array = array('url' => 'http://www.google.com');
echo json_encode($array);
?>

答案 1 :(得分:1)

Cletus的回答回答了您的问题,但我只想指出$.get$.getJSON之间的区别。

真的很简单:

// $.get is a shortcut for this:
$.ajax({
    method: "get"
});

// $.getJSON is just a shortcut for this:
$.ajax({
    method: "get",
    dataType : "json"
})

它们只是为您预先填充一些参数的便利方法。

相关问题