2012-07-14 117 views
1

这是我的索引文件,我想从fetch.php中获取值。 $('#loader').html($(response).fadeIn('slow'));这允许获取所有的值并将其显示在div = loader中。但我想要将单个返回值存储为javascript值。检索Success函数中的多个值并将它们存储到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> 

回答

1

使用json_encode在PHP和$.parseJSON jQuery中,像这样:

$.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更加清楚。

+0

好的,谢谢。在我的PHP文件中,我回显了4个值,所以我应该使用json。例如json_encode('title'=>'我的标题'),json_encode('description'=>'my_description')。 – user1525721 2012-07-14 15:46:52

+0

不,只需将它们添加到传递给'json_encode'的数组中 - 所以'array('title'=>'your title','description'=>'your description');'。我更新了我的答案以反映这一点。 – Martin 2012-07-14 15:55:21

相关问题