简体   繁体   中英

Retrieving multiple values inside the Success function and storing them to javascript variable

This is my index file where I want to get the values from the fetch.php. $('#loader').html($(response).fadeIn('slow')); This allows to get all the values and show it inside the div = loader. But I want to store individual return values to javascript values.

     $.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>

Use json_encode in PHP, and $.parseJSON in jQuery like so:

$.post("fetch.php?url="+$('#url').val(), {}, function(response) {
    var result = $.parseJSON(response);
    if (result.success) {
       var title = result.data.title;
       ...
    }
});

In your PHP you simply output something like:

json_encode(
  array(
    'success' => true,
    'data' => array(
               'title' => 'yourTitle',
               'description' => 'yourDescription'
              )
  )
 );

Another note

Please don't use @. If you aren't sure that index exists use correct validation, for example:

<?php if (is_array($url_title) && isset($url_title[0])): ?>
    <label class="title"><?php echo $url_title[0]; ?></label>
<?php endif; ?>

or

<label class="title"><?=is_array($url_title) && isset($url_title[0]) ? $url_title[0] : ''?></label>

EDIT:

Added extra indentation and extended the data array to make it more clear to the OP.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM