2012-12-19 2 views
0

PHP 개발자가 JS 도움말이 필요합니다! 나는 JS에 매우 익숙하고 이것을 이해할 수 없다.jQuery 별도의 함수 매개 변수에 url 매개 변수를 전달 하시겠습니까?

작은 jQuery 플러그인이 있습니다 gSearchhttp://gsearch.scottreeddesign.com/index.html 귀하의 페이지에서 Google 검색을 수행합니다. 그것은 POST/GET 기능으로 구현되지 않습니다. 함수 매개 변수 내에서 '검색어'를 정의해야합니다. 나는 그것을 수정하려고 노력하고있다.

내가 2 페이지가 :

search.html에를 포함

<form action="results.html"> 
    <input type="text" name="q" id="term"> 
    <input type="button" id="search_button" onclick="this.form.submit();"> 
</form> 

results.html에는 다음이 포함

<div id="search-results"></div> 
:

$("#search-results").gSearch({ 
    search_text : 'brian griffin', 
    count : 4, 
    site : 'wikipedia.org', 
    pagination : false 
}); 

을 몸에

이제 폼에서 검색어를 가져와 .gSearch 함수에 변수로 전달해야합니다. 나는 이것에 대해 어떻게 갈 것인가? URL 매개 변수를 가져 오는/반환하는 방법에 대한 게시물을 볼 수 있지만 변수로 바꾸고 다른 함수로 전달하는 방법을 설명하는 것을 찾을 수없는 것 같습니다. 나는 순수 PHP로 닫힌 눈으로 이것을 할 수 있지만 JS에 익숙하지 않다!

+0

location.search를 사용하면 자바 스크립트에서 GET 변수를 얻을 수 있습니다 .. – ppsreejith

+0

http://stackoverflow.com/questions/7825329/get-querionsring-with-dojo/7825382#7825382 dojo solution) –

답변

0
$('form').on('submit', function(e){ 
    e.preventDefault(); //stop default form submit 
    $('#search-results').gSearch({ 
     search_text: $('#term').val(), //the term to search 
     count: 4, //how many 
     site: 'wikipedia.org', //a site to match the search against 
     pagination: false //whether or not to use pagination 
    }); 
}); 

submit 양식을 캡처하고 preventDefault()로 중지하십시오. 그런 다음 id가 search-results 인 요소 (반환 된 결과가 추가됨)에 gSearch를 적용합니다. 객체 요청 내에서 일부 매개 변수를 정의합니다. 이것은 충분해야합니다.

0

당신이 JSON 객체로 가져 오기 매개 변수를 설정하려면이

$('#search_button').on('click', function(e) { 
    e.preventDefault(); 

    var $search = $('#term').val(); 

    // Assign it to the gSearch 
    $("#search-results").gSearch({ 
     search_text: $search, 
     count: 4, 
     site: 'wikipedia.org', 
     pagination: false 
    }); 


});​ 
+0

나는 다른 사람들을 테스트 할 기회를 얻지 못했다. 이것은 처음이었고 완벽했다. 모든 게시물에서 변수가 어떻게 작동하는지 더 잘 이해합니다. 고맙습니다! –

-1

, 사용하려고이

JSON.parse('{"' + decodeURI(location.search.substring(1)).replace(/&/g, "\",\"").replace(/=/g,"\":\"") + '"}') 
+0

이 코드는 불쾌한데, 왜 JSON.parse를 쓰겠습니까? 당신은 또한'decodeURIComponent'를 사용하지 않습니다 –

+0

내 의견을 읽지 않았습니까? 왜 내가 그것을 떨어 뜨린 지 말 했잖아. 'JSON.parse'를 사용할 필요가없고'decodeURIComponent'를 사용하지 않습니다. 자신의 코드로 JSON 문자열을 작성할 때마다 –

0

에 키/값 쌍을 읽을 수없는 내장 방법은 없습니다 JavaScript의 querystring. 쿼리 문자열에서 값, parse location.search을 얻으려면 :

var searchTerms = ""; 
if (/\bq=([^&]+)/.test(location.search)) { 
    searchTerms = decodeURIComponent(RegExp.$1); 
} 
$("#search-results").gSearch({ 
    search_text : searchTerms, 
    count : 4, 
    site : 'wikipedia.org', 
    pagination : false 
}); 

당신은 모든 자바 스크립트에서 POST 값을 읽을 수 없습니다. 이들은 서버 측에서만 사용할 수 있습니다.