du521521521 2016-04-11 12:51
浏览 37
已采纳

获取<li>标签的值到TextField

I am getting search results from a MySQL table from a string entered in an input text from a HTML page.

Using AJAX, when the user selects one of the result rows the browser is redirected to a PHP file.

What I need is to put the result on another TextField from the same page and not to open another page.

Here is the code that I have now:

PHP part that is sending the needed output results:

/************************************************
    Search Functionality
************************************************/

// Define Output HTML Formating
$html = '';

$html .= '<li class="result" >';
$html .= '<img src="iconos_especialidades/logo"  width="94" height="94"  />';
$html .= '<a target="_blank" href="urlString" >';
$html .= '   '.'<h3>nameString</h3>';
$html .= '</a>';
$html .= '</li>';

// Get Search
$search_string = preg_replace("/[^A-Za-z0-9]/", " ", $_POST['query']);
$search_string = $tutorial_db->real_escape_string($search_string);

// Check Length More Than One Character
if (strlen($search_string) >= 1 && $search_string !== ' ') {
    // Build Query
    $query = 'SELECT * FROM tb_especialidades WHERE especialidad LIKE "%'.$search_string.'%" OR especialidad LIKE "%'.$search_string.'%" ORDER BY especialidad';

    // Do Search
    $result = $tutorial_db->query($query);
    while($results = $result->fetch_array()) {
        $result_array[] = $results;
    }

    // Check If We Have Results
    if (isset($result_array)) {
        foreach ($result_array as $result) {

            // Format Output Strings And Hightlight Matches
            $display_function = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['especialidad']);
            $display_name = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['especialidad']);
            $display_url = 'opinar_doc_loc.php?id='.$result['id_especialidad'];

            if ($result['icono'] == ""){
            $display_logo = "nada.jpg";
            }
            else {
            $display_logo = $result['icono'] ;
            }

            // Insert Name
            $output = str_replace('nameString', $display_name, $html);



            // Insert URL
            $output = str_replace('urlString', $display_url, $output);
            // Insert LOGO
            $output = str_replace('logo', $display_logo, $output);
            // Output
            echo($output);
        }
    }else{

        // Format No Results Output
        $output = str_replace('urlString', 'javascript:void(0);', $html);
        $output = str_replace('nameString', '<b>No se ha encontrado la especialidad buscada.</b>', $output);
        $output = str_replace('functionString', 'Sorry :(', $output);
        // Insert LOGO
            $display_logo = "nada.jpg";
            $output = str_replace('logo', $display_logo, $output);

        // Output
        echo($output);
    }
}

And here is the JQuery/Ajax Part:

// Start Ready
$(document).ready(function() {  

    // Icon Click Focus
    $('div.icon').click(function(){
        $('input#search').focus();
    });

    // Live Search
    // On Search Submit and Get Results
    function search() {
        var query_value = $('input#search').val();
        $('b#search-string').text(query_value);
        if(query_value !== ''){
            $.ajax({
                type: "POST",
                url: "php/search.php",
                data: { query: query_value },
                cache: false,
                success: function(html){
                    $("ul#results").html(html);
                }
            });
        }return false;    
    }

    $("input#search").live("keyup", function(e) {
        // Set Timeout
        clearTimeout($.data(this, 'timer'));

        // Set Search String
        var search_string = $(this).val();

        // Do Search
        if (search_string == '') {
            $("ul#results").fadeOut();
            $('h4#results-text').fadeOut();
        }else{
            $("ul#results").fadeIn();
            $('h4#results-text').fadeIn();
            $(this).data('timer', setTimeout(search, 100));

        };
    });

});

How could I put the needed value from the database $result['id_especialidad'] on a TextField from the HTML page?

  • 写回答

2条回答 默认 最新

  • donglinxin8765 2016-04-11 13:12
    关注

    You can achieve this by returning a json object with more than one key. For example from php:

    <?php
      $result = array('id' => $result['id_especialidad'], 'data' => $output);
      echo json_encode($result);
    ?>
    

    Then from JS you can decode and handle as two separate pieces of data:

    $.ajax({
      type: "POST",
      url: "php/search.php",
      data: { query: query_value },
      cache: false,
      success: function(html){
        var response = $.parseJSON(html);
        $("#my_input_field").val(response.id);
        $("ul#results").html(response.data);
       }
     });
    

    EDIT -------

    I've added the correct id field from the query result (see above again), you will also need to edit the output from the no results part of the php file (after the 'else') to echo the json encoded array... for example:

    <?php
      $result = array('id' => 0, 'data' => $output);
      echo json_encode($result);
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?