使用JavaScript(或AJAX?)动态添加PHP / MySQL代码

时间:2022-12-05 14:08:42

I have to ask this question because I'm stuck, and I think its because my understanding of PHP and JavaScript is not fully formed. I think the way I've started to try doing this may be very very wrong but no one else's question hits on something that makes sense to me.

我不得不问这个问题因为我被卡住了,我认为这是因为我对PHP和JavaScript的理解还没有完全形成。我认为我开始尝试这样做的方式可能非常错误,但没有其他人的问题会对我有意义的事情产生影响。

Basicaly: I'm trying to have a JavaScript button on a form that will add additional form input boxes and at the same time add additional SQL code in PHP for inserting the data from the new forms to my database.

Basicaly:我正在尝试在表单上添加一个JavaScript按钮,它将添加其他表单输入框,同时在PHP中添加其他SQL代码,以便将新表单中的数据插入到我的数据库中。

My JavaScript looks like this..

我的JavaScript看起来像这样..

    function addElement2() {

var ni = document.getElementById('SQLphoneDiv'); 
    var numi = document.getElementById('theValue2'); 
    var num = (document.getElementById('theValue2').value -1 + 2); 
    numi.value = num; 
    var newdiv = document.createElement('div'); 
    var divIdName = 'SQLphoneDiv'+num+''; 
    newdiv.setAttribute('id',divIdName); 
    newdiv.innerHTML = ' <input type=hidden id=' +num+ ' value=' +num+ '> <?php      $insert_phone = "INSERT INTO phone (Phone_Cust_ID,Phone_Numb,Ext) VALUES    (\'$cust_ID[0]\',\'".$_POST[\'phone' +num+ '\']."\',\'".$_POST[\'ext' +num+ '\']."\')";    $add_phone = mysql_query($insert_phone); ?>'; 
    ni.appendChild(newdiv); 
    }

The "newdiv.innerHTML" is where all the code is, and when my JavaScript runs it sends it to a DIV on my PHP page.

“newdiv.innerHTML”是所有代码所在的位置,当我的JavaScript运行时,它将它发送到我的PHP页面上的DIV。

     <?php
    if (isset($_POST['submit'])) { 

         //add aditional phone numbers

         echo    '<input type="hidden"  value="0" id="theValue2" />';
         echo    '<div id="SQLphoneDiv"></div>';
     ?>

I've found that putting the echo parts outside of the "if" section makes the code actually show up when I hit my add button (at least the DIV's show up, of course it shows no PHP in live mode on Dreamweaver).

我发现将echo部分放在“if”部分之外会使代码实际显示在我点击我的添加按钮时(至少DIV的显示,当然它在Dreamweaver上的实时模式中没有显示PHP)。

So anyway, if I understand what I'm just figuring out this is totally wrong, because the PHP is set once the page is run, so trying to add more code after the fact makes no sense. Am I thinking right on this? How would you actually do this? Something with AJAX?

所以无论如何,如果我理解我刚刚弄清楚这是完全错误的,因为PHP在页面运行后设置,所以尝试在事实之后添加更多代码是没有意义的。我在想这个吗?你怎么会这样做?用AJAX做什么?

Any tips are greatly appreciated.

任何提示都非常感谢。

Nathan

1 个解决方案

#1


0  

PHP runs on the server before the page is sent to the client. JavaScript runs on the client. AJAX would be the way to go.

在将页面发送到客户端之前,PHP在服务器上运行。 JavaScript在客户端上运行。 AJAX将是最佳选择。

#1


0  

PHP runs on the server before the page is sent to the client. JavaScript runs on the client. AJAX would be the way to go.

在将页面发送到客户端之前,PHP在服务器上运行。 JavaScript在客户端上运行。 AJAX将是最佳选择。