duanpo7354
duanpo7354
2013-04-26 04:07

将表单输入存储在javascript变量中,然后将其值传递给php变量而不提交表单? [重复]

This question already has an answer here:

what I want to do is whenever a user fills his address in text field input I want to grab it on blur with javascript which I am able to do .. now how to pass this variable in a php variable so that i can use it for some operations ? the javascript file is called inside php file ..

</div>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • douchensou6495 douchensou6495 8年前

    Pull the data from the form elements first

    var dataObject = {};
    // #search is the form with search params
    $.each($('#form name').serializeArray(), function(i, field) {
    dataObject[field.name] = field.value;
    });
    

    then POST the data to the php

        $.ajax({  
             type: "POST",  
             url: "./api.php",  
            data: dataObject,
            success: function(dataout) {
                //dataout is what is returned from php
                //process it how you like from here
            }
        });
    

    in php do something with POST data

    <?php
       $element1 = $_POST["form_element_name1"];
       $element2 = $_POST["form_element_name2"];
       ...do something
       print $result;
    ?>
    

    the printed result is output to dataout in the ajax function.. process from there

    点赞 评论 复制链接分享
  • ds9567 ds9567 8年前

    PHP is a server-side language so after the page is called from the client's computer, there is no more PHP on the page but only converted to HTML. If you want to do something with the input in PHP on blur then you have to POST (easily done with jQuery) the data to a new instance of a PHP file so it can be compiled on the server.

    Page with the form

    $.post('name_of_php_file_to_send_data_to.php', {name: value}/* <-- data to pass to the PHP file*/,function(output) {
        // do something with the returned output of the PHP file
    });
    
    点赞 评论 复制链接分享

为你推荐