如何在PHP页面上执行GET以获取JSON对象?
我如何做到以下几点: 用户单击HTML页面上的“开始”按钮进入getnumber.php页面,该页面以以下形式返回数字10:{count:10}尝试谷歌 这是一个很好的起点。如何在PHP页面上执行GET以获取JSON对象?,php,jquery,Php,Jquery,我如何做到以下几点: 用户单击HTML页面上的“开始”按钮进入getnumber.php页面,该页面以以下形式返回数字10:{count:10}尝试谷歌 这是一个很好的起点。 并了解更多信息。 把它们放在一起,你就可以顺利上路了 <input type="button" id="btnID"/> $("#btnID").click(function(e){ e.preventDefault(); //prevent the default behavior of the butt
并了解更多信息。
把它们放在一起,你就可以顺利上路了
<input type="button" id="btnID"/>
$("#btnID").click(function(e){
e.preventDefault(); //prevent the default behavior of the button, or return false as @alecgorge pointed it out
$.get("process.php",function(data){
console.log(data);
},'json'); //<-- specifying the dataType as json will parse the json return by the server
});
看
在
getnumber.php
您需要PHP返回JSON格式的数据,即:
{"count": 10}
并指示返回的数据是JSON格式,响应中有一个标头
从JavaScript端,返回的值(前一个字符串)可以被求值并转换为JS对象。试试下面的方法
//you jquery code
$.getJSON('getnumber.php', function(data) {
alert(data); //returns your json_encoded number sent from getnumber.php page
});
//your php page
$arr = array("count" => 10);
echo json_encode($arr);
$.get('getnumber.php', function(data) {
var result = eval(data);
});
如果页面getnumber.php输出{count:10},则使用result.count获得结果
您还可以使用$.getJSON方法。可能需要
返回false代码>在单击事件的末尾。
$.get('getnumber.php', function(data) {
var result = eval(data);
});