donglian2106 2014-03-14 13:46
浏览 38

通过$ .ajax将javascript值传递给PHP

I have a dropdown with different options. When you select one option, the text inside the option, this, is shown below the dropdown menu. I do this with this code:

  var stadsnat_ar = new Array();
    $(".stadsnat_options").change(function() {

            stadsnat_ar.push($(".stadsnat_options option:selected").val()); //This value should be used in PHP to get correct data from MySQL

            var stadsnat = stadsnat = $(".stadsnat_options option:selected").text();    //show the text
            $('#teststat').show().append('<br>' + stadsnat);
    });

The whole idea is that you can choose multiple options, and then hit submit, to do a search in MySQL with the options you choosed. As you can see, I assign a array with the values of the options you choosed. How can I make the values in the array, visible to PHP?

I've tried this:

$.ajax({
    type: "POST",
    url: 'searchengine.php',
    data: {stad_value: stadsnat_ar},
    success: "",
    dataType: "json"
});

Then I do this:

<?php
echo $_POST['stad_value'];
?>

But nothing appears. Anyone?

  • 写回答

1条回答 默认 最新

  • duanhuang4306 2014-03-14 13:49
    关注

    You don't seem to have any problems exposing the values to PHP, all your problems seem to come after that stage.

    1. success needs to be a function that does something with the HTTP response data, not an empty string.
    2. If you tell jQuery to ignore what the server says the data is and treat it as JSON, then make sure you send JSON back
    3. echoing arrays probably isn't very useful.

    e.g.

    $.ajax({
        type: "POST",
        url: 'searchengine.php',
        data: {stad_value: stadsnat_ar},
        success: doSomething,
        dataType: "json"
    });
    
    function doSomething(data) {
        $('body').text(data.join("-"));
    }
    

    and

    <?php
    header("Content-Type: application/json");
    echo json_encode($_POST['stad_value']);
    ?>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应