使用Javascript/JQuery检索JSON GET数据

Ben*_*Ben 6 html javascript jquery json get

我想要做的是从在线Web服务中检索JSON数据,该服务在MySQL数据库中搜索并找到某个字符串,并在HTML页面上使用Javascript显示它.

我正在努力的是实际显示结果数据.

我的HTML页面的相关区域如下所示:

<form onSubmit="results()">
    <fieldset>
        <label for="area">First digits of postal code:</label>
        <input name="area" type="text" maxlength="4" placeholder="AB12" required />
        <input type="submit" value="Search" name="search" />
    </fieldset>
</form>



<script type="text/javascript" src="jquery/jquery.min.js"></script>
<script type="text/javascript" src="cordova-2.3.0.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">

function results(){
    $.ajax({
        url: 'http://www.entertainmentcocktail.com/cp/index.php?area=AB12',
        dataType: 'jsonp',
        jsonp: 'jsoncallback',
        timeout: 5000,
        success: function(data, status){
            $.each(data, function(i,item){
                var place = '<h1>'+item.location+'</h1>'
                + '<p>'+item.id+'</br>';

                output.append(place);
            });
        },
        error: function(){
            output.text('There was an error loading the data.');
        }
    });
};
</script>

<div id="place">
<h3>Places near your location</h3>
</div>
Run Code Online (Sandbox Code Playgroud)

GET数据的页面是http://www.entertainmentcocktail.com/cp/index.php,其搜索变量为"area".测试样品是?area = AB12.

rsp*_*rsp 4

该服务似乎没有正确地将 JSON 对象包装在括号中,因此它不能作为 JSONP 工作。

请参阅:http ://www.entertainmentcocktail.com/cp/index.php?area=AB12&jsoncallback=TEST

它返回:

TEST[{"id":"5","name":"The Red Lion", ... ,"confirmed":"0"}]
Run Code Online (Sandbox Code Playgroud)

虽然它应该返回:

TEST([{"id":"5","name":"The Red Lion", ... ,"confirmed":"0"}]);
Run Code Online (Sandbox Code Playgroud)

您将无法使用它,因为它不是有效的 JSONP

更新:

从评论中回答更多信息 - 如果您控制服务器端脚本,则尝试更改:

while($row = mysql_fetch_assoc($result)) { $records[] = $row; }
echo $_GET['jsoncallback'] . json_encode($records);
Run Code Online (Sandbox Code Playgroud)

到:

while($row = mysql_fetch_assoc($result)) { $records[] = $row; }
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
Run Code Online (Sandbox Code Playgroud)

看看是否有效。

更新2:

回答另一个评论。您实际上初始化了output变量吗?例如,开头是这样的:

var output = $('#place').append('<div/>');
Run Code Online (Sandbox Code Playgroud)

你真的调用了你的results函数吗?必须使用以下方式调用它:

results();
Run Code Online (Sandbox Code Playgroud)

或者使用 jQuery 方式在某处注册为事件处理程序:

$('form').submit(results);
Run Code Online (Sandbox Code Playgroud)

但然后添加:

return false;
Run Code Online (Sandbox Code Playgroud)

到函数末尾results以防止页面重新加载。

请参阅此演示:http://jsbin.com/uziyek/1/edit - 它似乎有效。

另一个问题:

您的代码似乎还有另一个问题,area=AB12 参数被硬编码到您的 URL 中。相反,您应该做的是从表单中获取值并将其发送。