在 Success 函数中检索多个值并将它们存储到 javascript 变量中
Retrieving multiple values inside the Success function and storing them to javascript variable
这是我的索引文件,我想从获取中获取值.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 更清晰。
相关文章:
- 如何使用Doctrine在MongoDB中存储Javascript代码
- 有人知道如何在本地存储javascript函数所做的css更改吗
- .txt文件和.json文件同样适合存储javascript对象
- 是否可以存储javascript函数调用并在设置某些变量时执行它
- 如何在外部存储javascript变量(没有服务器)的值
- 如何在PHP会话中存储javascript数组
- 本地存储 javascript 变量到 php
- 如何在rails/devise中存储Javascript/AJAX变量
- 我可以在mySQL数据库中存储JavaScript对象吗?
- 用于存储 Javascript 应用程序的持久本地数据的轻量级解决方案
- 在元素上使用css属性content来异常存储javascript的信息
- 如何正确存储javascript模板,使其不会;t实例化了多次
- windows8存储javascript应用程序,从web下载和保存图像
- 获取sencha touch中本地存储javascript文件的属性
- 浏览器是读取/存储Javascript文件中的所有内容,还是仅读取/存储它们需要的内容
- 可以使用数据属性来存储Javascript'状态'
- 离线webapp -存储JavaScript对象
- 从本地存储javascript的对象数组中删除一个对象
- 如何在jsp字符串中存储javascript变量值
- 数组存储javascript