0

ユーザーがアイテムに言語IDを追加できるシンプルなページがあります。このページは、ajax呼び出しを実行して、レコードのリストをロードします。すべてのレコードがリストとしてdivにロードされます。

各リスト項目はフォームであるため、ユーザーがlang idを入力すると、更新を押すとajax呼び出しがオフになり、データベースが更新され、更新されたばかりのレコードを除いたレコードがリストに再ロードされます。

jquery呼び出しはページの読み込みで機能しますが、フォームアイテムを送信すると、送信したページ内で再読み込みするのではなく、phpスクリプトに送られます。

最初の呼び出しが「ページに」読み込まれるのに、フォームの送信が読み込まれない理由。また、レコードごとにフォームを使用することをお勧めします。または、jqueryでそれを行うためのより良い方法があります。

ajax呼び出しを行う元のphpスクリプト(sort_language.php)

   <script id="source" language="javascript" type="text/javascript">

   function run(){
// get form data
    var eng = $('#rec #eng').val();
    var cym = $('#rec #cym').val();

    // put form data in a JSON
    var data_json = {'eng':eng, 'cym':cym};

    //post to php script to update database and return html list
    $.ajax({
      type: 'post',
      url: 'ajax/lang_api.php',
      data: data_json,
      beforeSend: function() {
        // before send the request, display a "Loading..." message
        $('#records').html('Loading...');
      },
      timeout: 10000,        // sets timeout (10 seconds)
      error: function(xhr, status, error) { alert('Error: '+ xhr.status+ ' - '+ error); },
      success: function(response) { $('#records').html(response); }
    });

    return false; //this should stop page reload
}


$(document).ready(function()
{
    $("#rec").submit(function()
    {
        run()
    });
    run()
});



 </script>
</head>
<body>

<div id="record_wrapper">
<h1>Records by title</h1>
<div id="records">
    Waiting for records to load....
</div>

これは、リストを作成してデータベースを更新するphpスクリプトです。

//get lang post variables if they exist
$eng_id = $_POST['eng'];
$cym_id = $_POST['cym'];
//debug - check post values are correct visually
echo 'eng' . $eng_id . ' cym ' . $cym_id;

function create_list() {    
//generate html list
$html .='   <ul>';

    //grab records from DB which have not been updated with language value to display
    if (!$query = mysql_query("SELECT `id`, `title-245` FROM `records` WHERE `catalog_lang-040` = 'eng' ORDER BY `title-245`")) {
        echo mysql_error();
    }
    //generate each item in list as a form 
    //set form id to rec
    while($row = mysql_fetch_array($query))
    {
        $html .= '  <li><form action="ajax/lang_api.php" method="post" id="rec">' . $row['title-245'] . ' <input type="text" name="cym" size="3" /><input type="hidden" name="eng" id="eng" value="' . $row['id'] . '" /> <input type="submit" value="submit" /></form></li>
        ';                                                                                      
    }

$html .= '  </ul>';
//return the html to be used
return $html;
}

//if eng and cym ids are submitted then update DB, otherwise just return the html required.
//check value is set using isset
if (isset($eng_id) && isset($cym_id)) {

if (!is_numeric($eng_id)) { $rehtml= 'Invalid English ID'; }
if (!is_numeric($cym_id)) { $rehtml= 'Invalid Welsh ID'; }

//sql to go here to update db ith language value

//and then get new list to output.
  echo create_list();
//post undefined so just return list (for first page load/refresh)  
}else{
// output the html
  echo create_list();
}

おそらく明らかな何かが欠けていますが、初めてjquery/jsで遊んでいます。

そして、これがlang_api.phpによって作成されたHTMLリストです。これは、sort_language.phpの「レコードがロードされるのを待っています」を置き換えてrecordsdivにロードされます。

eng417 cym 21   
<ul>    
 <li><form action="ajax/lang_api.php" method="post" id="rec">18th - 19th century ballads collection , 18th - 19th century,  <input type="text" name="cym" size="3" /><input type="hidden" name="eng" id="eng" value="417" /> <input type="submit" value="submit" /></form></li>
            <li><form action="ajax/lang_api.php" method="post" id="rec">1st The Queen's Dragoon Guards Collections , 1685 -,  <input type="text" name="cym" size="3" /><input type="hidden" name="eng" id="eng" value="1001" /> <input type="submit" value="submit" /></form></li>
            <li><form action="ajax/lang_api.php" method="post" id="rec">Aberconway Library , 20th century -,  <input type="text" name="cym" size="3" /><input type="hidden" name="eng" id="eng" value="101" /> <input type="submit" value="submit" /></form></li>
            <li><form action="ajax/lang_api.php" method="post" id="rec">Aberfan Disaster Archive , Mainly 1966 -,  <input type="text" name="cym" size="3" /><input type="hidden" name="eng" id="eng" value="303" /> <input type="submit" value="submit" /></form></li>
            <li><form action="ajax/lang_api.php" method="post" id="rec">Abergavenny Local History Collection , Prehistory to the present day,  <input type="text" name="cym" size="3" /><input type="hidden" name="eng" id="eng" value="1030" /> <input type="submit" value="submit" /></form></li>
            <li><form action="ajax/lang_api.php" method="post" id="rec">Alister Hardy Religious Experience Archive , 1924 -,  <input type="text" name="cym" size="3" /><input type="hidden" name="eng" id="eng" value="1042" /> <input type="submit" value="submit" /></form></li>
            <li><form action="ajax/lang_api.php" method="post" id="rec">Almanacs Collection , 1700 - 1850,  <input type="text" name="cym" size="3" /><input type="hidden" name="eng" id="eng" value="740" /> <input type="submit" value="submit" /></form></li>
            <li><form action="ajax/lang_api.php" method="post" id="rec">Ammanford Local Studies Collection , 1880s -,  <input type="text" name="cym" size="3" /><input type="hidden" name="eng" id="eng" value="939" /> <input type="submit" value="submit" /></form></li>
            <li><form action="ajax/lang_api.php" method="post" id="rec">Anderson Collection , 17th - 20th century,  <input type="text" name="cym" size="3" /><input type="hidden" name="eng" id="eng" value="407" /> <input type="submit" value="submit" /></form></li>
</ul>
4

2 に答える 2

0

「最初の呼び出しが「ページに」読み込まれるのに、フォームの送信が読み込まれない理由はありません。」

あなたのコードは正確にそうするように指示しているからです。サーバー側のコードでは、通常のhtmlフォームであり、jQueryやajaxにバインドされていない一連のフォーム要素を生成します。したがって、送信ボタンを押すと、htmlフォームから期待されることを実行します。投稿を実行し、現在のページをサーバーの応答に置き換えます。

「また、レコードごとにフォームを使用することをお勧めします。または、jqueryでそれを行うためのより良い方法があります。」

すべてのフォーム要素の送信をajax呼び出しにバインドすると、機能する可能性がありますが、これを非常に洗練されたソリューションとは呼びません。むしろ、特定のクラスを持つすべてのボタンにバインドされた単一のjqueryajax投稿を使用したいと思います。

$("button.recordsubmit").live("click", function() { // ajax submit code });

フォームではなくサーバー側でこれらのボタンを生成します。また、レコードdiv全体をリロードするのではなく、個々のレコードdivをターゲットにすることを検討する必要があります。これにより、変更されたコンテンツのみが置き換えられます。

于 2012-07-23T10:07:56.853 に答える
0

ここにはいくつかの問題があります。

  1. それぞれのフォームを作成するためのアプローチはお勧めしません<li>。任意の要素の任意のイベントにラッチできるため、単純なボタンを配置してクリックイベントをそれにバインドできます。
  2. 失敗する理由jquery.submit()は、ヘルパーメソッド(およびクリック、ホバーなど)であり、これらのメソッドは、ページが読み込まれたときにページに存在する要素にのみバインドするためです。一方、要素を動的に追加するので、使用する必要があるのはliveまたはon:です。

    $('button').on('click',function(){//do your stuff});
    

jquery.on()jquery.live( )を見てください

編集:

初めてページをロードするときは、ajax呼び出しは必要ありません。phpで作成するだけです。

ユーザーがボタンをクリックすると、jquery.load()メソッドを使用してリスト全体を置き換えることができます。そのためには、リストをdivでラップする必要があります。

<div id="listWrapper">....</div>

次にjqueryを使用します。

$('button').on('click',function()
    $('#listWrapper').load('ajax/lang_api.php',data_json);
});

これにより、phpスクリプトが自動的に呼び出され、div内のlsitがphpスクリプトから返されたリストに置き換えられます。

于 2012-07-23T10:12:39.213 に答える