使用Jquery Json P将外部数据加载到phonegap中

时间:2013-03-26 13:59:15

标签: jquery cordova jsonp

我有以下json对象,我从我的本地mysql。

<([{"ID":"1","Title":"Chicken & Chili","Price":"$8.99","ImageURL":"\/images\/dinner\/chicchili.jpg","Serves":"2","Description":"This unique and delicious chicken chili is a much-requested meal around our house. I think you'll find it's a nice change of pace from the typical beef version."},{"ID":"2","Title":"Chicken Franchase","Price":"$9.99","ImageURL":"\/images\/dinner\/chicfran.jpg","Serves":"2","Description":"Served in a lemon and butter sauce"},{"ID":"3","Title":"Salmon","Price":"$14.99","ImageURL":"\/images\/dinner\/salmon.jpg","Serves":"1","Description":"A simple soy sauce and brown sugar marinade, with hints of lemon and garlic, are the perfect salty-sweet complement to rich salmon fillets."}]);

我使用以下代码将json对象导入iPhone模拟器。我成功获得了屏幕上的标题和价格,但没有图像。有什么方法可以获得图像?或者我在编码中遗漏了一些东西。有什么建议吗?

$(document).ready(function(){
var output = $('#output');
$.ajax({
url: 'http://localhost/Backend/getDinner.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
  $.each(data, function(i,item){ 
    var Menu_Dinner = '<li><a href="detail.html?id=' + item.ID + '">' +
      '<img src="images/dinner/'+ item.ImageURL + '">' +
    '<h2 class="ui-li-heading">' + item.Title + '</h2 >' + 
    '<h2>' + 'Price: ' + item.Price + '</h2>'+ '</a></li>';
    output.append(Menu_Dinner);
  });
},
error: function(){
  output.text('There was an error loading the data.');
}

}); });

1 个答案:

答案 0 :(得分:2)

我怀疑您需要更改链接路径。例如:

  1. 如果您的数据库中的图片网址路径为:images/dinner/picture.jpg,则代码必须为:'<img src="' + item.ImageURL + '">'
  2. 如果您的图片网址路径只是picture.jpg,那么您可以使用现有代码。
  3. 我不知道模拟器是否有可以查看的控制台窗口,如果它确实将以下行添加到success函数的末尾并检查每个列表项的href属性:< / p>

    console.log($("#output").html());
    

    作为一方,尽量减少操作DOM的次数。所以试试这个:

    var temp = "";
    $.each(data, function(i,item){ 
      var Menu_Dinner = '<li><a href="detail.html?id=' + item.ID + '">' +
        '<img src="images/dinner/'+ item.ImageURL + '">' +
        '<h2 class="ui-li-heading">' + item.Title + '</h2 >' + 
        '<h2>' + 'Price: ' + item.Price + '</h2>'+ '</a></li>';
      temp += Menu_Dinner;
    });
    output.append(temp);