如何通过ajax向php发送第二个值


How to send a second value via ajax to php

我使用ajax在数据库中搜索值并填充下拉列表。这是我的ajax代码:

function searchq6(){
    var searchstate = $("input[name='region']").val();
    var searchTxt = $("input[name='suburb']").val();
    $.post("search-suburb.php", {searchVal: searchTxt, st:searchstate})
    .done(function(sbb) {
        $("#sbb").html(sbb);
    }); 
}

在这里,我得到一个用户输入的地区,并在数据库中搜索该地区的郊区。这是我的php代码:

$output = '' ;
if (isset($_POST['searchVal'])){
$searchq = $_POST['searchVal'];
$st = $_POST['st'];
$query = mysqli_query($link, "SELECT DISTINCT title FROM `wp_locations` WHERE state='".$st."'  AND `title` LIKE  '%".$searchq."%' LIMIT 10")or     die("Could not search!");
if (!mysqli_query($link,$query))
{
        echo("Error description: " . mysqli_error($link));
}
$count = mysqli_num_rows($query);
if($count == 0){
    $output = '<option>No results!</option>';
}else{
while($row = mysqli_fetch_array($query)){
    $suburb = $row['title'];
    $postcode = $row['postcode'];
?>
    <option value="<?php echo $suburb; ?>"><?php echo $suburb; ?>    </option>
<?php
} // while
} // else
} // main if

我想做的是,将postcode值发送到另一个输入框。这就是我的html的外观

Suburb:* <input type="text" name="suburb" list="sbb" required size="30" value="<?php echo $suburb;  ?>" onkeyup="searchq6()" id="output">
        <datalist id="sbb" name="taskoption6" >
                <option> </option>
        </datalist>
Postcode:* <input type="number" name="postcode" required value="<?php echo $postcode;  ?>"  id="postcode">

简单地添加$("#postcode").html(postcode);是行不通的。如何从php文件发送值?

只需创建一个具有三个值的数组。1.成功是真是假2.值的数据数组,如果成功,则为true,否则为null3.成功值为假的错误原因。

因此,您的错误结果之一将是:

$result = ['success' => false, 'data' => null, 'error' => 'error connecting db'];

您的成功结果将是:

$result = ['success'=> true, 'data'=> ['suburbs'=> $suburbs, 'pincode' => $pincode], 'error' => null];

现在将这个结果数组作为json发送。

echo json_encode($result);

然后在jquery中解析Json并填充reult。

在PHP文件中:

// Output is array, will be send as JSON data
$output = array("suburbs"=>'', "postcodes"=>array());
if (isset($_POST['searchVal'])){
    $searchq = $_POST['searchVal'];
    $st = $_POST['st'];
    $query = mysqli_query($link, "SELECT DISTINCT title FROM `wp_locations`     WHERE state='".$st."'  AND `title` LIKE  '%".$searchq."%'     LIMIT 10")or     die("Could not search!");
    if (!mysqli_query($link,$query)) {
        echo("Error description: " . mysqli_error($link));
    }
    $count = mysqli_num_rows($query);
    if($count == 0){
        $output["suburbs"] = '<option>No results!</option>';
    }else{
        while($row = mysqli_fetch_array($query)){
            $suburb = $row['title'];
            $postcode = $row['postcode'];
            $output["suburbs"] .= "<option value='"$suburb'">$suburb  </option>";
            $output["postcodes"][$suburb] = $postcode;
        } // while
    } // else
    // Send result
    echo json_encode($output);
} // main if

在HTML的AJAX部分:

// Make global variable that holds POSTCODES:
var postcodes = {};
function searchq6(){
    var searchstate = $("input[name='region']").val();
    var searchTxt = $("input[name='suburb']").val();
    $.post("search-suburb.php", {searchVal: searchTxt, st:searchstate})
    .done(function(response) {
        var responseObj = jQuery.parseJSON(response);
        $("#sbb").html(responseObj["suburbs"]);
        postcodes = responseObj["postcodes"];
    }); 
}

在HTML:中

 Suburb:* <input type="text" onselect="change_post(this)" onchange="change_post(this)" name="suburb" list="sbb" required size="30"  value="<?php echo $suburb;  ?>" onkeyup="searchq6()" id="output">
    <datalist id="sbb" name="taskoption6" >
            <option> </option>
    </datalist>
 Postcode:* <input type="number" name="postcode" required value="<?php echo $postcode;  ?>"  id="postcode">
 <script>
      //var postcodes = { "1":"First", "2":"Second", "3":"Third", "4":"Fourth" };
        function change_post(out) {
            //console.log(postcodes[ out.value ]!=undefined);
            if ( postcodes[ out.value ]!=undefined )
                document.getElementById("postcode").innerHTML = postcodes[ out.value ];
        }
 </script>