How to send variable to php from javascript and return the result back to JS

后端 未结 2 1107
礼貌的吻别
礼貌的吻别 2021-01-29 05:57

I have this code.

var book = document.getElementById(\'txtBook\').value;
switch(book.toUpperCase())
    {
        case \"GEN\": var bk = \"101\"; break;
                 


        
相关标签:
2条回答
  • 2021-01-29 06:29

    You need to use ajax.

    $.get('getbook.php', {book: $('#txtBook').val()}, function(data) {
      // here you get your data and deal it 
    });
    
    0 讨论(0)
  • 2021-01-29 06:42

    The simplest way is applying ajax.

    Serve script(getbook.php):

    $bookId = $_POST['book'];
    //do some search stuff
    $rows = getBookInfo($bookId);
    $result = array('searchResult' => $rows);
    
    header('Content-Type: application/json');
    echo json_encode($result);
    

    Client script(remeber to include js for jquery):

    postData = {book: bookId};
    $.ajax({
         type: 'POST',
         url: '/getbook.php',
         data: postData,
         dataType: 'JSON',
         success: function (jsonObj) {
            //use jsonObj.serachResult as array
         }
       });
    
    0 讨论(0)
提交回复
热议问题