簡體   English   中英

用Ajax將JS變量傳遞給PHP的方法?

[英]Method for passing JS variable to PHP with Ajax?

我有一個Codeigniter應用程序插入了wordpress網站。 我需要根據我視圖中html選定的選項值來修改php中的簡碼。 簡碼將表單添加到我的html頁面。 我在想我需要使用Ajax將數據從JS移到PHP。 我對如何做到這一點感到困惑。 這是必須完成的基本順序(減去Ajax或其他所需方法):

在我看來,我需要具有以下組件:

<html>
    <select id="select-service">
      <option value="volvo">Volvo</option>
      <option value="saab">Saab</option>
      <option value="mercedes">Mercedes</option>
      <option value="audi">Audi</option>
    </select>

//This is where I am putting the short code I made in JS
<?php echo do_shortcode("shortCode GOES HERE"); ?>

</html>
<script>
    function getService() {
        var serviceItem = $('#select-service option:selected').text();
        shortCode = "[wpi_checkout item='" + serviceItem + "']" ;
        //AN AJAX SEQUENCE HERE?
        var postUrl = GlobalVariables.baseUrl + '/ajax_serviceitem'; 
        $.ajax({
            url: postUrl,
            method: 'post',
            data: shortCode,
            success: function(data) {
                alert(data);
            }
        });
    }
    $(document).ready(getService);
    $('select').on('change', getService);
</script>

在我的控制器中,我想我需要一個像這樣的函數:

public function ajax_serviceitem() {
    $shortcode = $_POST('shortCode')
    $this->load->view('myview', $shortcode);
    //I am lost as to what to do next 
}

我是在正確的軌道上還是在使這一問題復雜化?

function getService() {
        var serviceItem = $('#select-service option:selected').val();
        data = {'shortCode':serviceItem};
        //AN AJAX SEQUENCE HERE?
        var postUrl = GlobalVariables.baseUrl + '/ajax_serviceitem'; 
        $.ajax({
            url: postUrl,
            type: "POST",
            dataType: 'json',
            data : data,
            success: function(data) {
                alert(data);
            }
        });
    }

========================我看到的另一個解決方法是==================

public function ajax_serviceitem() {
    $shortcode = $_POST['shortCode']
    $this->load->view('myview', $shortcode);
    //I am lost as to what to do next 
}

您可以嘗試解決此問題的方法:

JS:

function getService() {
    var serviceItem = $('#select-service option:selected').val();
    data = {'shortCode':serviceItem};
    //AN AJAX SEQUENCE HERE?
    var postUrl = GlobalVariables.baseUrl + '/ajax_serviceitem'; 
    $.ajax({
        url: postUrl,
        type: "POST",
        dataType: 'json',
        data : data,
        success: function(response) {
            if (response.status == 'success') {
                console.log("Success Request");
                $("#view_selector").html(response.my_view_file);
            } else {
                console.log("Fail Request");
            }
        }
    });
}

PHP的:

public function ajax_serviceitem() {
    if ($this->input->is_ajax_request()) {
        $shortcode =  $this->input->post('shortCode');
        if (!empty($shortcode)) {
            $my_view_file = $this->load->view('myview', $shortcode, TRUE);
            $data['status'] = 'success';
            $data['my_view_file'] = $my_view_file;
        } else {
            $data['status'] = 'error';
            $data['my_view_file'] = "";
        }
        echo json_encode($data);
        exit;
    } else {
        redirect('login/logout'); // Logout URL here
    }
}

希望對您有所幫助。

這里的問題是,盡管php工作是在服務器上完成的,但是傳遞回的變量在JS中,因此它將無法工作。 我通過向視圖添加一些php來解決問題,從視圖中收集選項並從中構建簡短代碼:

//First: In css I hid all the elements that the short code produces


//This select box is built by a foreach routine in my controller.
<html>
    <select id="select-service">
      <option value="volvo">Volvo</option>
      <option value="saab">Saab</option>
      <option value="mercedes">Mercedes</option>
      <option value="audi">Audi</option>
    </select>

//This is where I am putting the short code.  I am grabbing $service['id'] from my database in my controller and sending it to the view. I am building a bunch of divs that reflect the values of the select options here rather than in the controller.  I have to do this because the wordpress do_shortcode() hook will only work in the view.
<?php foreach($available_services as $service) { 
    $shortcode = "[wpi_checkout item='" . $service['id'] "' title ='session_ID' callback_function='ea_paypalcallback']"; ?>
    <div id="<?php echo $service['id'] ?>" class="shortcode"><?php echo do_shortcode($shortcode)?></div>
<?php } ?>  

</html>

然后,我在Ajax send上成功運行以下命令以進行其他操作:

var selServiceId = $('#select-service').val();
$('#' + selServiceId ).find(':submit').click();

做到了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM