2012-08-07 2 views
1

저는이 프로젝트에서 클라이언트가 선택하는 것에 따라 입력 상자를 자동 완성 할 수 있도록 반환 값을 얻으려고합니다.자바 스크립트 코드가 실행되고 있지 않습니다.

그러나이 코드는 실행되지 않으며 이유를 알지 못합니다. 제거 할 때 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 =

<? 

// 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); 
?> 
에 대한 PHP 파일입니다입니다

이 파일은 정보를 보낼 것입니다. 그래서 자바 스크립트는 이제까지 당신의 PHP에서

답변

1

:

<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를 사용하는 경우 6,

그리고 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 -

좋아요 그래서 기본적으로 당신이 원하는이 ...

자바 스크립트입니다 :

:

$firstName = $_POST['first']; 

MySQL의 쿼리는 다음과 같을 것이다 POST의 PARAM 수신

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' 
    ); 
}); 

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

다음을 모두 추가하십시오. 귀하의 MySQL 필드를 연관 배열 배열 (key => value)로 변환 한 다음 json_encode 및 배열을 반환하십시오.

+1

코드가 어디에 있든 src = "js/site.js"를 사용해야합니까? –

+0

프로젝트 트리에서 "js"라는 디렉토리/폴더를 만든 다음 그 안에 "site.js"라는 파일을 만듭니다. 그런 다음 ''태그가없는 사용자 정의 스크립트를 넣습니다. 이것은 본질적으로 똑같은 결과를 낳지 만 모범 사례를 사용합니다. – Valjas

+0

외부 JS에 대한 제안과 함께 기본 프로젝트 트리 예제를 포함하도록 답변을 업데이트했습니다. – Valjas

1
<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")); 
+0

나는 backgroundScript.php에서 값을 얻는다. –

2

뭔가를해야와 양식 필드를 대체합니다 형식화 된 html은 .val()을 통해 dom에 삽입하려고 시도합니다. 이 메서드는 양식 필드의 값을 설정하는 데 사용되며 html의 전체 청크는 삽입하지 않습니다. 대신 .append() 또는 .html()을 사용하고 위에서 Phil이 제안한 작업을 수행하십시오. 스크립트를 여러 블록으로 나눕니다.

+0

marc .append() 메서드를 사용한다는 것은 무엇을 의미합니까? –

+0

http://api.jquery.com/append/ –

0

하지

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

이어야한다

당신은 이전에 그것을 사용에 jQuery를 포함 할 필요가
$("#contacts").on('change', function() { 
관련 문제