如何使用Ajax运行外部的PHP文件并显示结果在同一个页面如何使用、页面、结果、文件

2023-09-10 20:33:43 作者:誓言,如尘般染指留念。

现在,我用下面的脚本按钮,点击它在新窗口中打开

Right now I'm using below script for button click which opens in new window

<script>function myFunction()
{
   window.open("ouput.php");
}
</script>

当用户点击按钮的结果,从 output.php 必须在同一窗口底部追加

不过,我需要的是。 如何使用Ajax来执行PHP文件? 我使用这个code使用jQuery但没有结果是:

But what I need is when user clicks button the results from output.php must be appended in the same window at the bottom. How to execute PHP file using Ajax? I'm using this code with jQuery but there is no result:

$.get( "out.php", 
   function( data ) {          
      document.write(data.Molecule);                  
      $( "output" ).html("Molecule: "+data.Molecule );           
      alert( "Load was performed." );                 
   }, 
   "json" );
});
});

如何运行一个外部的PHP文件,得到的结果和在同一网页上显示呢?

How to run an external PHP file, get results and display it in the same webpage?

推荐答案

AJAX调用是普通请求,因此都会自动执行PHP文件。

AJAX calls are regular requests so any PHP file is automatically executed.

$(输出)将选择所有&LT;输出&GT; 标签。我怀疑你的意思是一个对象ID =输出(这是在页面的底部)

$("output") will select all <output> tags. I suspect you meant an object with ID=output (which is at the bottom of the page)

下面是一个纠正JS:

$.get( "out.php", function( data ) {
    // replace content of #output with the response
    $( "#output" ).html( "Molecule: " + data.Molecule );
    // append the response to #output
    //$( "#output" ).append( "Molecule: " + data.Molecule );
    alert( "Load was performed." );
}, "json" );

如果响应不是有效的JSON,这将导致错误(而不是叫警告)。如果是这样的话,你可以提醒并检查这样的反应:

If the response is not valid JSON this will cause an error (and not call the alert). If that's the case you can alert and check the response like this:

$.get( "out.php", function( data ) {
    alert( data );
});

这不会对JSON,如果它不是有效的,因此不会引发错误。

This won't expect JSON and therefore not throw an error if it's not valid.