这是我的索引文件,我想从获取中获取值.php。 $('#loader').html($(response).fadeIn('slow'));
这允许获取所有值并将其显示在div = 加载器中。但是我想将单个返回值存储到 javascript 值中。
$.post("fetch.php?url="+$('#url').val(), {}, function(response){
//var $res=$(response);
//var title =$res.filter('.title').text(); (not wrking)
//$('#title').val(title);
$('#loader').html($(response).fadeIn('slow'));
$('.images img').hide();
$('#load').hide();
$('img#1').fadeIn();
$('#cur_image').val(1);
});
});
<input type="hidden" name="cur_image" id="cur_image" />
<div id="loader">
<div align="center" id="load" style="display:none"><img src="load.gif" /></div>
</div>
<input type="hidden" name="title" id="title" />
(e.g. I want to store the title value from fetch.php to this hidden field)
**fetch.php**
<div class="info">
<label class="title">
<?php echo @$url_title[0]; ?>
</label>
<br clear="all" />
<label class="url">
<?php echo substr($url ,0,35); ?>
</label>
<br clear="all" /><br clear="all" />
<label class="desc">
<?php echo @$tags['description']; ?>
</label>
<br clear="all" /><br clear="all" />
<label style="float:left"><img src="prev.png" id="prev" alt="" /><img src="next.png" id="next" alt="" /></label>
<label class="totalimg">
Total <?php echo $k?> images
</label>
<br clear="all" />
</div>
在
PHP中使用json_encode
,在jQuery中使用$.parseJSON
如下:
$.post("fetch.php?url="+$('#url').val(), {}, function(response) {
var result = $.parseJSON(response);
if (result.success) {
var title = result.data.title;
...
}
});
在你的PHP中,你只需输出如下的东西:
json_encode(
array(
'success' => true,
'data' => array(
'title' => 'yourTitle',
'description' => 'yourDescription'
)
)
);
另一个注意事项
请不要使用 @。如果不确定索引是否存在,请使用正确的验证,例如:
<?php if (is_array($url_title) && isset($url_title[0])): ?>
<label class="title"><?php echo $url_title[0]; ?></label>
<?php endif; ?>
或
<label class="title"><?=is_array($url_title) && isset($url_title[0]) ? $url_title[0] : ''?></label>
编辑:
添加了额外的缩进并扩展了数据数组,使其对 OP 更清晰。