【问题标题】:How to post data from a php file to another php file to add the data to database without using ajax如何在不使用 ajax 的情况下将数据从 php 文件发布到另一个 php 文件以将数据添加到数据库
【发布时间】:2015-05-03 20:29:14
【问题描述】:

我有一个 php 文件 (todo.php & todo.js),它从用户那里收集一些数据并使用 ajax 将收集到的数据发布到另一个要添加到数据库的 php 文件 (add.php) 中。我的问题是我不想使用 ajax 将数据发布到第二个 php 文件 (add.php)。我该如何改变这个。我已提取代码并显示如下

//todo.js 从 todo.php 调用来验证新的 todoEntry

function addToDo(){
    var descField = document.getElementById('nDesc');
    var percField = document.getElementById('nPerc');

    if( !validateField(descField) ){
        alert("Description " + errorMessage);
        return;
    }
    if( !validatePercentField(percField) ){
        alert("Percentage " + errorMessage);
        return;
    }

    //use ajax to post new entries to add.php which will add them
    ajaxCall(encodeURI('add.php?description=' + descField.value  
           + '&percentage=' + percField.value), function(response){
        if( response.status == 200 ){
            if( response.responseText.toString().indexOf
        ("success") != -1 ){
                //clear values
                descField.value = "";
                percField.value = "";

                //refresh table
                fetchToDo();
            }
            else
                alert(response.responseText);
        }
    });
    }

     From add.php:
    <?php
    session_start();

    if( !isset($_SESSION['username']) ){
        die("Your Session has expired. Please re-login to continue");
    }

    //get required data
    $description = trim(isset($_GET['description']) ? urldecode($_GET   
        ['description']) : "");
    $percentage = trim(isset($_GET['percentage']) ? urldecode($_GET
        ['percentage']) : "");

    //validate data
    if( empty($description) || empty($percentage) ){
        die("All fields are required!");
    }

    //connect to database
    include('connect.php');

    //insert data
    $stmt = $mysqli->prepare("INSERT INTO todo_entry VALUES (NULL, ?, NOW 
        (), NOW(), ?, ?)");
    $stmt->bind_param("ssi", $_SESSION['username'], $description,
         $percentage);
    $stmt->execute();

    if( $stmt->affected_rows > 0 ){
        $stmt->close();
        echo "success";
    }
    else{
        echo "An Error Occured: " . $stmt->error;
        $stmt->close();
    }

    //close database
    $mysqli->close();
    ?>

【问题讨论】:

  • 创建一个表单给第二页和方法=发布动作。您将在 $_POST 的第二页上获得所有数据。
  • 这个逻辑有一个严重的缺陷。确实,您正在谈论您 100% 知道的非常基本的主题。您在谈论的是表单功能。正如@anantkumarsingh 所说的那样。生活比您想象的工作流程更轻松。
  • 是的,如果您不想使用表单加载另一个页面,Ajax 是这里唯一的选择。

标签: php html mysql ajax


【解决方案1】:

cURL 之于 PHP 就像 AJAX 之于 JS。如果你想直接从 PHP 调用一个脚本而不需要浏览器向服务器发出额外的请求,你可以使用 cURL。这是一个简单的函数。

/*
 * Makes an HTTP request via GET or POST, and can download a file
 * @returns - Returns the response of the request
 * @param $url - The URL to request, including any GET parameters
 * @param $params - An array of POST values to send
 * @param $filename - If provided, the response will be saved to the 
 *    specified filename
 */
function request($url, $params = array(), $filename = "") {
    $ch = curl_init();
    $curlOpts = array(
        CURLOPT_URL => $url,
        // Set Useragent
        CURLOPT_USERAGENT => 
            'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:29.0) 
                    Gecko/20100101 Firefox/29.0',
        // Don't validate SSL 
        // This is to prevent possible errors with self-signed certs
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true
    );
    if(!empty($filename)){
        // If $filename exists, save content to file
        $file2 = fopen($filename,'w+') 
            or die("Error[".__FILE__.":".__LINE__."] 
                    Could not open file: $filename");
        $curlOpts[CURLOPT_FILE] = $file2;
    }
    if (!empty($params)) {
        // If POST values are given, send that shit too
        $curlOpts[CURLOPT_POST] = true;
        $curlOpts[CURLOPT_POSTFIELDS] = $params;
    }
    curl_setopt_array($ch, $curlOpts);
    $answer = curl_exec($ch);
    // If there was an error, show it
    if (curl_error($ch)) die(curl_error($ch));
    if(!empty($filename)) fclose($file2);
    curl_close($ch);
    return $answer;
}

【讨论】:

  • 如果 2 个 PHP 文件在同一台服务器上(OP 没有告诉但看起来像,因为在 'add.php' 当前 ajax URL 之前没有任何内容),一个简单的include()第二个可以完成这项工作,而不会无缘无故地强调 http 服务器 ;-)
  • 他当前的解决方案是基于 AJAX 的,这意味着脚本需要某些 post/get 值。使用包含将需要他重写脚本,因为这些值不会出现。但我同意,如果可能的话,包括它会是一个更好的解决方案。
  • 更改 add.php 中的变量名称仍然比实现过度的 curl 方法更快;-) 顺便说一句,您仍然可以在脚本中声明任何 $_POST$_GET 值,其中包括add.php 如果您真的不想更改它并保留某种可以包含或发布 add.php 的双重解决方案。
  • @Capsule,就像我说的那样,如果这是一个合理的解决方案,那么我完全同意这是一个更好的解决方案,但它可能会也可能不会像您暗示的那么简单。如果在其他地方使用 add.php 并输出一堆 XML 或 JSON 怎么办。或者如果像你说的那样,它在另一台服务器上。这真的取决于。
  • 是的,但这有很多如果。显然情况并非如此,并且 OP 显然不知道他在做什么(无意冒犯,每个人在某些时候都是初学者)所以我们不要让他认为 curl 是一切的答案。但不要误会我的意思。在另一个上下文/更复杂的环境中,是的,绝对是一个很好的答案!
猜你喜欢
  • 2020-12-29
  • 1970-01-01
  • 2011-10-02
  • 1970-01-01
  • 1970-01-01
  • 2016-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多