繁体   English   中英

javascript代码未被执行

[英]javascript code is not being executed

我正在研究这个项目,我正在尝试获取返回值,以便根据客户选择的内容自动填充输入框。

但是这段代码没有执行,我不知道为什么。 当我删除src="jquery area" $(#dropdown).on是一个未定义的方法; 不确定该怎么做。

<script  type="text/javascript"  src="http://code.jquery.com/jquery-latest.min.js">
//$.post(url, [data], [callback], [callback type])

    ("#dropdown").on('change', function() {//when you select something from the dropdown function run and will switch the data
        $.post("backgroundScript.php", {
                uid: $(this).val()
            },
             function(data) {
                 $("#first").val(data.first);
               $("#last").val(data.last);
               // etc.;
            }, 'json'
        );

    });
</script>

这是我的完整代码

try {  
  # MySQL with PDO_MYSQL  
  $DBH = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);  
  $DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

  //$DBH->prepare('SELECT first FROM contacts');
}  
catch(PDOException $e) { 
    echo "I'm sorry, I'm afraid I can't do that.";  
    file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);   
}  
//get query
$FNresult=$DBH->query('SELECT first FROM contacts'); 
//set fetch mode
$FNresult->setFetchMode(PDO::FETCH_ASSOC);

$dropdown = "<select name='contacts' id='contacts' >";

while($row =$FNresult->fetch()) {

  $dropdown .= "\r\n<option value='{$row['first']}'>{$row['first']}</option>";
 // echo getLN();

}

$dropdown .= "\r\n</select>";

echo $dropdown;

//}
/*
//                  Get last name

function getLN(){
    $query = "SELECT last FROM contacts";
    $LNresult=mysql_query($query);

    $last;
    while($row = mysql_fetch_assoc($LNresult)) {

        $last = "{$row['last']}";

    }
    echo $last;
}//end getLN
*/

$DBH = null; 
?>
<!-- javascript on client-side -->
<script  type="text/javascript"  src="http://code.jquery.com/jquery-latest.min.js">
//$.post(url, [data], [callback], [callback type])

    ("#dropdown").on('change', function() {//when you select something from the dropdown function run and will switch the data
        $.post("backgroundScript.php", {
                uid: $(this).val()
            },
             function(data) {
                 $("#first").val(data.first);
               $("#last").val(data.last);
               // etc.;
            }, 'json'
        );

    });
</script>


<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js">

/*("#dropdown").on('connection', function (stream) {
  console.log('Ah, we have our first user!');
});*/</script>

<form action="insert.php" method="post">
First Name: <input type="text" id="first" name="first"><br>
Last Name: <input type="text" id="last"><br>
Phone: <input type="text" id="phone"><br>
Mobile: <input type="text" id="mobile"><br>
Fax: <input type="text" id="fax"><br>
E-mail: <input type="text" id="email"><br>
Web: <input type="text" id="web"><br>
<input type="Submit">
</form>

这是我在输出页面=上编辑的新脚本

<script type="text/javascript"
     src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>    

//$("#dropdown-parent").on('change','#dropdown', function() { // replace dropdown-parent
    $("#contacts").on('change','#dropdown', function() {

        $.post("backgroundScript.php", { 
                uid: $(this).val() 
            }, 
             function(data) { 
                 $("#first").val(data.first); 
                 $("#last").val(data.last); 
                 // etc.; 
            }, 'json' 
        ); 
    }); 
</script>

这是backgroundScript.php =的php文件

<?

// background script

// retrieve data based on $_POST variable, set to $returnArray

$returnArray = $_POST[array(
         'first' => firstName,
         'last' => lastName,
)];

/****************************
 * the structure of returnArray should look something like
     array(
         'first' => firstName,
         'last' => lastName,

     )*/
echo json_encode($returnArray);
?>

此文件将发送信息,因此javascript将替换表单字段与指定区域中保存的内容

看来您的PHP脚本正在返回一些格式化的html,然后您尝试通过.val()插入到dom中。 该方法用于设置表单字段的值,而不是插入整个html块。 尝试使用.append().html() ,再加上Phil建议的内容 - 将脚本分成多个块。

<script  type="text/javascript"  src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>    
    $("#dropdown-parent").on('change','#dropdown', function() { // replace dropdown-parent
        $.post("backgroundScript.php", { 
                uid: $(this).val() 
            }, 
             function(data) { 
                 $("#first").val(data.first); 
                 $("#last").val(data.last); 
                 // etc.; 
            }, 'json' 
        ); 

    }); 
<script>

在PHP中你应该有这样的东西

echo json_encode(array('first' => $some_value, 'last' => "Other value"));

您需要在使用之前包含jQuery:

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
  // Your Code Here
</script>

更好的是使用外部JS:

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="js/site.js"></script>

如果您使用HTML5,则甚至不需要type="text/javascript"

<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="js/site.js"></script>

更好的是使用jQuery CDN

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="js/site.js"></script>

另外,正如其他人所指出的那样,一定要在jQuery工厂的开头使用$ $('#dropdown')

- 更新 -

关于项目树的进一步说明,大多数基本项目树看起来像这样:

root/
 |--css/
 |--images/
 |--js/
    |--site.js
 |--index.html

- 更新2 -

$.post示例

$.post({
    'somescript.php', // Script your posting to
    { 
        someParam1: someData1, // $_POST['someParam1']
        someParam2: someData2
        // etc etc
    },
    function(response){
        // Do something with JSON response upon successful post
        alert(response);
    },
    'json' // Tells the script that JSON will be returned
});

- 更新3 -

好吧基本上你想做的就是......

使用Javascript:

var dropdown = $('#dropdown');

dropdown.bind('change', function(){
    $post.(
        'backgroundScript.php', 
        { 
            first: dropdown.val() 
        },
        function(response) {
            $('#first').val(response.first);
            $('#last').val(response.last);
            // Repeat for all of your form fields
        },
        'json'
    );
});

接收POST参数:

$firstName = $_POST['first'];

MySQL查询将类似于以下内容:

$sth = $dbh->prepare('SELECT *
    FROM contacts
    WHERE first = :first');
$sth->bindParam(':first', $first, PDO::PARAM_STR);
$sth->execute();

然后将所有MySQL字段添加到关联数组数组(key => value),然后添加json_encode并返回数组。

不能

("#dropdown").on('change', function() {

$("#contacts").on('change', function() {

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM