Jquery ajax调用将转到php脚本,而不重新加载页面


Jquery ajax call going to php script and not reloading page

我有一个简单的页面,允许用户向项目添加语言id。页面通过执行ajax调用来加载记录列表。所有记录都作为列表加载到div中。

每个列表项都是一个表单,所以当用户输入lang-id时,他们按下update,ajax调用就会停止,更新数据库,并用记录(减去刚刚更新的记录)重新加载列表。

jquery调用适用于页面加载,但如果您提交表单项,它将转到php脚本,而不是在您提交的页面中重新加载。

为什么最初的调用加载在"页面中",但表单提交没有。另外,对每条记录使用一个表单是个好主意,或者有没有更好的方法来使用jquery。

执行ajax调用的原始php脚本(sort_langue.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列表,它加载到记录div中,取代了sort_language.php 中的"等待加载记录"

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>

这里有几个问题:

  1. 我不推荐您为每个<li>创建表单的方法。由于您可以锁定任何元素上的任何事件,因此只需放置一个简单的按钮并将click事件绑定到它即可
  2. 失败的原因是jquery.submit()是一个辅助方法(以及单击、悬停等),并且这些方法仅在加载时绑定到页面上存在的元素。另一方面,动态添加元素,因此需要使用liveon:

    $('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脚本,并用php脚本返回的列表替换div中的lsit。

"为什么初始调用加载了‘in page’,而表单提交却没有。"

因为你的代码告诉要这么做。在你的服务器端代码中,你生成了一组表单元素,它们是普通的html表单,无论如何都不绑定到jQuery或ajax。因此,当你按下任何提交按钮时,它都会执行html表单所期望的操作:发布帖子,并用服务器的响应替换你的当前页面。

"此外,对每条记录使用一个表单是个好主意,或者有没有更好的方法来使用jquery。"

如果您将所有表单元素的submit绑定到ajax调用,它就可以工作——但我不认为这是一个非常优雅的解决方案。我宁愿使用一个绑定到所有具有特定类的按钮的jquery ajax帖子,比如

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

并在服务器端生成这些按钮,而不是表单。此外,您应该考虑不重新加载整个记录div,而是针对单个记录div,这样只有更改后的内容才会被替换。