js在函数调用中传递变量

时间:2018-01-31 15:26:08

标签: javascript jquery ajax function variables

我正在建立我的第一个网站,我认为这是一个愚蠢的问题,但我被困住了。我对运行查询的脚本进行了ajax调用,并为数组提供了一些信息。

ajax-call在一个函数中分离。 我无法使用输入值传递给函数变量。

使用静态字符串/ int,它可以工作:

$("#searchIt").click(function(){    
    var inputbranche = $('#branche').val(); #pass the value of select
    var inputplz = $('#plz').val();         #pass the value of input
    window.history.replaceState(null, null, "?branche="+inputbranche+"&plz="+inputplz); //this works fine with the variables
    $('#fulllink').val(window.location.href);
    $('#sm').attr('data-url', window.location.href);
    if(searches == 0) {
        scrollTo("#topscroll");
    } else {
        scrollTo("*[data-resultnumber='1']");
    }
    searchCompanies('tischler', '44444'); //<---- here is the problem: if I use here inputbranche and inputplz, it´s not working...

});


function searchCompanies(branche, plz) {
    searches++;
    var shownbranchename = $('#branchename').val();
    $.ajax({
            url: "url/to/script",
            type: "GET",
            data:'wheretostart=0&branche='+branche+'&plz='+plz,
            success: function(data){
                var count = 0;
                if(data['success'] == 1) {
                    while(data[count] != 0 ) {
                        if(jQuery.inArray(data[count]['id'], shownIDs) == -1) {
                            var txt = "<div data-resultnumber='"+number+"' data-companyid='"+data[count]['id']+"' class='col-sm-6 col-md-4 p0'><div class='box-two proerty-item'><div class='item-thumb'><a href='property-1.html' ><img src='assets/img/demo/property-3.jpg'></a></div><div class='item-entry overflow'><h5><a href='property-1.html'> "+data[count]['companyname']+" <i class='fa fa-check-circle' aria-hidden='true'></i></a></h5><div class='dot-hr'></div><span class='pull-left'><b> Branche :</b> "+data[count]['branches']+" </span><h3 class='pull-right'><span class='fa fa-star checked'></span><span class='fa fa-star checked'></span><span class='fa fa-star checked'></span><span class='fa fa-star'></span><span class='fa fa-star'></span></h3><p style='display: none;'>"+data[count]['shorttext']+"</p><div class='property-icon'>&nbsp;<i class='fa fa-map-marker' aria-hidden='true'></i> "+data[count]['companyzipcode']+" | <i class='fa fa-users' aria-hidden='true'></i> "+data[count]['employeecount']+" | <i class='fa fa-envelope' aria-hidden='true'></i> 355  </div></div></div></div>";
                            $("#list-type").append(txt);
                            shownIDs.push(data[count]['id']);
                        }
                        count++;
                        number++;
                        if(shownbranchename !== branche) {
                            $('#branchename').text(branche);
                        }
                    } 
                } else {
                    var txt = data['errors'];
                    $("#list-type").append(txt);
            }
        }
    });
}

带搜索的HTML:

 <fieldset>
     <div class="row">
          <div class="col-xs-12">
               <div class="form-group">
                    <label for="branche">Branche:</label><br>
                    <select name="branche" id="branche" class="form-control" title="Branche">
                         <option <?php if($_GET['branche'] == "architekten") {echo "selected";} ?> value="architekten">Architekten</option>
                         <option <?php if($_GET['branche'] == "dachdecker") {echo "selected";} ?> value="dachdecker">Dachdecker</option>
                         <option <?php if($_GET['branche'] == "geruestbauer") {echo "selected";} ?> value="geruestbauer">Gerüstbauer</option>
                         <option <?php if($_GET['branche'] == "klempner") {echo "selected";} ?> value="klempner">Klempner</option>
                         <option <?php if($_GET['branche'] == "maler_und_lackierer") {echo "selected";} ?> value="maler_und_lackierer">Maler und Lackierer</option>
                         <option <?php if($_GET['branche'] == "maurer_und_betonbauer") {echo "selected";} ?> value="maurer_und_betonbauer">Maurer und Betonbauer</option>
                         <option <?php if($_GET['branche'] == "metallbauer") {echo "selected";} ?> value="metallbauer">Metallbauer</option>
                         <option <?php if($_GET['branche'] == "Ofen-_und_Luftheizungsbauer") {echo "selected";} ?> value="Ofen-_und_Luftheizungsbauer">Ofen- und Luftheizungsbauer</option>
                         <option <?php if($_GET['branche'] == "schornsteinfeger") {echo "selected";} ?> value="schornsteinfeger">Schornsteinfeger</option>
                         <option <?php if($_GET['branche'] == "strassenbauer") {echo "selected";} ?> value="strassenbauer">Straßenbauer</option>
                         <option <?php if($_GET['branche'] == "tischler") {echo "selected";} ?> value="tischler">Tischler</option>
                         <option <?php if($_GET['branche'] == "zimmerer") {echo "selected";} ?> value="zimmerer">Zimmerer</option>
                     </select>
               </div>
          </div>
          <div class="col-xs-12">
               <div class="form-group">
                    <label for="plz">Postleitzahl:</label>  
                    <input type="number" id="plz" name="plz" class="form-control" <?php if($_GET['plz'] != null) {$temp = $_GET['plz']; echo "value='$temp'";} else {echo "placeholder='Postleitzahl'";} ?>>
               </div>
          </div>
     </div>
 </fieldset>

 <fieldset>
     <div class="row">
          <div class="col-xs-12">  
               <button type="button" id="searchIt" class="button btn largesearch-btn" value="Search" type="submit">Search</button>
          </div>  
     </div>
  </fieldset>  

这是php代码,希望这有助于......

<?php
header('Content-type: application/json');
ini_set("display_errors", 1);
session_start();
$return = array();
/* PHP lookup: Looks up the matching Companies in the DB */
require_once ('../global_konfi.php');
require_once ('../functions/functions.php');
$pdo = new  pdo ("mysql:host=dddd; dbname=" . $mysql['database'], 
$mysql['user'], $mysql['password']);
if(brancheIsBranche($_GET['branche']) == true) {
    $plz = $_GET['plz'];
    $limitstart = $_GET['wheretostart'];
    $perpage = "15";
    $statement = $pdo->prepare("SELECT COUNT(*) as anzahl FROM handwerksbetriebe WHERE general_branche = :branche AND general_visible = 1 AND general_state = 1 AND assignment_zipcoderange LIKE :zipcode LIMIT $limitstart, $perpage");
    $statement->bindValue(':branche', $_GET['branche']);       
    $statement->bindValue(':zipcode', "%;$plz;%", PDO::PARAM_STR);       
    if ($statement->execute()) { 
        $row = $statement->fetch();
        if ($row['anzahl'] >= 1) {
            $statement = $pdo->prepare("SELECT * FROM handwerksbetriebe WHERE general_branche = :branche AND general_visible = 1 AND general_state = 1 AND assignment_zipcoderange LIKE :zipcode LIMIT $limitstart, $perpage"); #statemetn vorbereiten
            $statement->bindValue(':branche', $_GET['branche'], PDO::PARAM_STR);       
            $statement->bindValue(':zipcode', "%;$plz;%", PDO::PARAM_STR);  
            $statement->execute();
            $count = 0;
            $temp = array();
            while($row = $statement->fetch()) {
                $temp = [
                    'id' => $row['general_id'],
                    'shorttext' => $row['general_shorttext'],
                    'companyname' => $row['general_title'],
                    'verified' => $row['general_verified'],
                    'assignmentcount' => $row['general_assignmentcount'],
                    'employeecount' => $row['general_employeecount'],
                    'averagerating' => $row['general_averagerating'],
                    'companyzipcode' => $row['contact_zipcode'],
                    'branches' => $row['general_branche'],
                ];
                array_push($return, $temp);
                $count++;
            }
            $return['errors'] = "0";
            $return['success'] = "1";
        } else {
        $return['errors'] = "noexecute";
        $return['success'] = "0";
        }

    } else {
        $return['errors'] = "noexecute";
        $return['success'] = "0";
    }
} else { 
$return['errors'] = "norealinput";
$return['success'] = "0";
}
echo json_encode($return);

3 个答案:

答案 0 :(得分:0)

您需要将click事件放在

$(document).ready() {//click event here}
function searchCompanies(var1, var2) {//...code}

以便渲染dom,jQuery可以按ID找到HTML元素。

如果您已经这样做了,请发布更多代码(特别是HTML和JS),以便我们更好地帮助解决您的问题

答案 1 :(得分:0)

我已经切换了ajax函数调用的位置。现在它有效。不知道为什么:

$("#searchIt").click(function(){

        var inputbranche = $('#branche').val();
        var inputplz = $('#plz').val();
        window.history.replaceState(null, null, "?branche="+inputbranche+"&plz="+inputplz);
        searchCompanies(inputbranche, inputplz);
        $('#fulllink').val(window.location.href);
        $('#sm').attr('data-url', window.location.href);
        if(searches == 0) {
        scrollTo("#topscroll");
        } else {
        scrollTo("*[data-resultnumber='1']");
        }


    });

答案 2 :(得分:-1)

这是你用jQuery做的:

$.ajax({
  ...
  context: {key: "1"},
  success: function(data){
   const contextValue = this.key;
  }
});

确保在处理() => {...}事件时不使用箭头功能$.ajax,因为它会给this一个与您期望的不同的含义this - 箭头函数不会修改HttpService.post = jest.fn(() => { return Promise.reject({ payload: 'rejected' }); }); ,在这种特殊情况下,这是一个理想的效果。