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

时间:2012-07-23 09:50:29

标签: php jquery ajax list

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

每个列表项都是一个表单,因此当用户输入lang id时,他们按下update并且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列表,这将加载到记录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>

2 个答案:

答案 0 :(得分:0)

“任何想法为什么初始调用加载'页面',但表单提交没有。”

因为您的代码确切地说明了这一点。在您的服务器端代码中,您生成一堆表单元素,这些表单元素是常规的html表单,不以任何方式绑定到jQuery或ajax。因此,当您按下任何提交按钮时,它将执行html表单所期望的操作:发布帖子,并将当前页面替换为服务器的响应。

“每个记录使用一个表单也是一个好主意,或者有更好的方法来使用jquery。”

如果你将所有表单元素的提交绑定到ajax调用,它可以工作 - 但我不会称之为非常优雅的解决方案。我宁愿使用绑定到具有某个类的所有按钮的单个jquery ajax post,例如

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

并在服务器端生成这些按钮而不是表单。此外,您应该考虑不重新加载整个记录div,而是以单个记录div为目标,因此只更换已更改的内容。

答案 1 :(得分:0)

你有几个问题:

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

    $('button').on('click',function(){//do your stuff});
    
  3. 查看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脚本返回的列表。