【问题标题】:get content back to javascript from PHP file in JSON format以 JSON 格式从 PHP 文件中将内容返回到 javascript
【发布时间】:2013-04-04 21:50:26
【问题描述】:

当从 jQuery Mobile 脚本向指定的 PHP 文件发送请求时,不会返回任何内容,也不会将任何内容附加到 html 文件中。这是页面的网址:

localhost/basket/newstext.html?url=http://www.basket-planet.com/ru/news/9235

newstext.html:

<head>
<script src="js/newstext.js"></script> 
</head>
<body> 
<div data-role="page" id="newstext"> 
  <div data-role="content"> 
    <div id="textcontent"></div> 
    </div> 
  </div> 
</body> 

newstext.js:

var serviceURL = "http://localhost/basket/services/"; 
$('#newstext').bind('pageshow', function(event) { 
var url = getUrlVars()["url"]; 
$.getJSON(serviceURL + 'getnewstext.php?url='+url, displayNewsText); 
}); 

function displayNewsText(data){ 
  var newstext = data.item; 
  console.log(newstext);
  $('#textcontent').text(newstext); 
  $('#textcontent').trigger('create'); 
} 

function getUrlVars(){ 
//it displays in the alert perfectly, shortening the message here 
} 

getnewstext.php:

<?php 
include_once ('simple_html_dom.php'); 
$url = $_GET['url']; 
$html = file_get_html(''.$url.''); 

$article = $html->find('div[class=newsItem]'); 
$a = str_get_html(implode("\n", (array)$article)); 
//parse the article 
header("Content-type: application/json");
echo '{"item":'. json_encode($a) .'}';
?>

我认为我的问题是我如何在 PHP 脚本中对 $a 变量进行编码。 $a 变量包含各种 html 标记...如何将其附加到 html 文件中?

【问题讨论】:

  • 确保在回显内容之前设置了内容标题,header("Content-type: application/json"); 它可能就像 jquery 一样简单/您的浏览器不知道如何处理返回的文本块
  • 还可以尝试对 displayNewsText 函数内的数据进行 console.debug 以查看该变量中的格式。您需要打开浏览器的控制台(咨询 google)才能查看输出
  • 我更新了文本...你能检查一下我是否正确更新了吗?对于newstext.html,控制台中的响应是空的......在另一个页面上,我从mysql查询中获取数据,响应是带有数据的正确php文件。此页面的响应为空...

标签: php jquery json jquery-mobile


【解决方案1】:

你有这条线的地方:

$.getJSON(serviceURL + 'getnewstext.php?url='+url, displayNewsText);

改为:

$.getJSON(serviceURL + 'getnewstext.php?url='+url, displayNewsText, function(response){
    $('#elem').append(response);
});

其中,#elem 是您希望将 PHP 文件返回的数据附加到的元素的名称。

【讨论】:

  • 这不是我在做的吗? displayNewsText 是处理响应的函数......所以我应该摆脱 displayNewsText?
  • 糟糕,我没有意识到这是一个函数调用;你需要做的是添加另一个参数,因为第一个 getJSON 参数是 url,第二个是要传递给 URL 的数据,第三个是处理响应的函数调用。我认为您只需要添加另一个参数即可。
  • 或者,为了更清楚起见,您可能希望使用 jQuery 提供的普通 $.get 方法,这样可以显式设置成功/错误/完成回调。 api.jquery.com/jQuery.get
  • 该功能可以与 .bing('pageshow'...) 一起使用吗?我认为 pageshow 仅适用于 jQuery Mobile,但我可能错了。所以唯一的功能就是getJSON
  • $.get()?是的,如果您将$.getJSON() 替换为$.get(),这将起作用。 $.getJSON 只是一个使用 $.get() 的辅助方法,但是使用 $.get(),你有 .success()、.error() 和 .complete() 方法,这可能会更清楚地看到你在做什么使用 AJAX 响应。
猜你喜欢
  • 2010-10-15
  • 2014-04-29
  • 1970-01-01
  • 1970-01-01
  • 2013-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-25
相关资源
最近更新 更多