Я пытаюсь реализовать приложение, которое в настоящее время находится в процедурном формате в Laravel 5. Пользователь вводит некоторые параметры в форму поиска, передает данные, а затем результаты отображаются в виде ряда графиков. Экран загрузки, который отображается, пока данные, полученные и организованные, сделаны с некоторым HTML на странице обработки PHP, как показано здесь (оригинальный, процедурный метод):
// create an array to store data for each record per iteration $recordArray = array(); // create an array to represent citation values to ignore, ie not interested in any publications // with less than 4 citations $ignore = array(0, 1, 2, 3); // create a counter variable to use for progress bar $counter2 = 1; // create a variable to store time for loading screen $timeDecimal = round(($len*$avg), 2); // turn time into readable format if ($timeDecimal > 59.99) { $minutes = round(($timeDecimal/60), 0, PHP_ROUND_HALF_DOWN); while ($timeDecimal > 59.99) { $timeDecimal -= 60; $seconds = round($timeDecimal, 0); }; } else { $minutes = 0; $seconds = round($timeDecimal, 0); }; // panel to display records loading progress, js updates current record in #progressPanel echo "<div class='panel panel-primary' id='alertBox'> <div class='panel-heading'> <h1 class='panel-title'> PROGRESS<span class='glyphicon glyphicon-info-sign'></span> </h1> </div> <div class='panel-body'> <p id='progressPanel'></p> <p>The <strong>maximum</strong> estimated time for this query is " .$minutes. " minutes & " .$seconds. " seconds</p> <h2> <button type='submit' class='back btn btn-primary' onclick='goBack()'> <span class='glyphicon glyphicon-remove'></span> <strong>Cancel</strong> </button> </h2> </div> </br> <div id='processing' hidden> <h4 class='text-primary'>Processing retrieved data...</h4> <div class='progress progress-striped active'> <div class='progress-bar' style='width: 100%''></div> </div> </div> </div>"; // iterate through all records, perform search for each 100 records (max per call) and tabulate data for ($i = 1; $i <= $len; $i+=100) { // set search parameters for current iteration (first record = 1, 101, 201, 301 etc.) $search_array = array( 'queryParameters' => array( 'databaseId' => 'WOS', 'userQuery' => $queryJournal1 . $queryJournal2 . $queryJournal3 . $queryTitle1 . $queryTitle2 . $queryTitle3, 'editions' => array('collection' => 'WOS', 'edition' => 'SCI'), 'timeSpan' => array('begin' => "1970-01-01", 'end' => (date("Ymd"))), 'queryLanguage' => 'en' ), 'retrieveParameters' => array( 'count' => '100', 'sortField' => array( array('name' => $sortType, 'sort' => 'D') ), 'firstRecord' => $i ) ); // gather search response for current iteration try { $search_response = $search_client->search($search_array); } catch (Exception $e) { echo $e->getMessage(); }; // turn Soap Client object from current response into SimpleXMLElement $xml = new SimpleXMLElement($search_response->return->records); // save variable names for global use, author, citations and publication year $citations = ""; $pubyear = ""; $country = ""; // iterate through current data set and tabulate onto webpage plus store in variable foreach($xml->REC as $record) { // create array for this REC data $authors = []; ob_flush(); // flush anything from the header output buffer flush(); // send contents so far to the browser echo "<script type='text/javascript'> setRecord(" .$counter2. "); </script>"; // authors foreach($record->static_data->summary->names->name as $thisAuthor) { array_push($authors, $thisAuthor->full_name); } // country (if exists) if (isset($record->static_data->item->reprint_contact->address_spec->country)) { $country = (string)$record->static_data->item->reprint_contact->address_spec->country; } else { $country = ""; }; // publication year $pubyear = (string)$record->static_data->summary->pub_info->attributes()->pubyear; // number of citations, if zero then finish populating array then 'break' out of loop entirely (not interested in zero cited records) if (!in_array($record->dynamic_data->citation_related->tc_list->silo_tc->attributes(), $ignore)) { $citations = (string)$record->dynamic_data->citation_related->tc_list->silo_tc->attributes(); } else { break 2; }; // for this iteration map all the values recorded into a temporary array variable, aRecord (equivalent to one row of data in table) $arecord = array("authors"=>$authors, "pubyear"=>$pubyear, "country"=>$country, "citations"=>$citations ); // pass the data from this iteration into the array variable '$recordArray', after all iterations, each element in $recordArray will be a single record or row of data for a single journal array_push($recordArray, $arecord) ; } // increment for next record $counter2+=100; }; // finished loading records, display 'processing' load bar echo "<script type='text/javascript'>showLoadBar();</script>"; ob_flush(); // flush anything from the header output buffer flush(); // send contents so far to the browser
Если функция setRecord()
связана с связанным скриптом, script'js
:
// function that will overwrite current record in info panel function setRecord(current) { document.getElementById('progressPanel').innerHTML = "<strong>Loading record " + current + "</strong>"; };
Таким образом, в #alertBox
есть текст, в котором говорится «Загрузка записи 1», «Загрузка записи 101», «Загрузка записи 201» и т. Д.
Однако в Laravel я не могу просто вставить этот HTML-код в модель, которая обрабатывает данные, поскольку она не может связывать файлы CSS и JS. Вот модель SoapWrapper.php
которая выполняет ту же функцию, что и выше, и вызывается контроллером:
<?php namespace App\Models; use SoapClient; use Illuminate\Http\RedirectResponse; use Redirect; class SoapWrapper { // SOAP exchange for WoS authentication public $auth_client; public $auth_response; // SOAP exchange for WoS search public $search_client; public $search_response; // number of records found public $len; // XML data to send as SOAP Request to WoS public $data; // array to store records public $records = []; // function to iterate and store all relevant data returned from SOAP exchange public function iterateWosSearch($submit) { // variable to store average time/record retrieval (based on calculations) $avg = 0.08; // create a variable to store time for loading screen $timeDecimal = (round((($submit->len)*$avg), 2)); // create an array to represent citation values to ignore, ie not interested // in any publications with less than 4 citations $ignore = array(0, 1, 2, 3); // create a counter variable to use for progress bar $counter = 1; // turn time into readable format (mins & secs, rather than just secs) if ($timeDecimal > 59.99) { $minutes = round(($timeDecimal/60), 0, PHP_ROUND_HALF_DOWN); while ($timeDecimal > 59.99) { $timeDecimal -= 60; $seconds = round($timeDecimal, 0); }; } else { $minutes = 0; $seconds = round($timeDecimal, 0); }; // panel to display records loading progress, js updates current record in #progressPanel echo "<div class='panel panel-primary' id='alertBox'> <div class='panel-heading'> <h1 class='panel-title'> PROGRESS<span class='glyphicon glyphicon-info-sign'></span> </h1> </div> <div class='panel-body'> <p id='progressPanel'></p> <p>The <strong>maximum</strong> estimated time for this query is " .$minutes. " minutes & " .$seconds. " seconds</p> <h2> <button type='submit' class='back btn btn-primary' onclick='goBack()'> <span class='glyphicon glyphicon-remove'></span> <strong>Cancel</strong> </button> </h2> </div> </br> <div id='processing' hidden> <h4 class='text-primary'>Processing retrieved data...</h4> <div class='progress progress-striped active'> <div class='progress-bar' style='width: 100%''></div> </div> </div> </div>"; ob_flush(); // flush anything from the header output buffer flush(); // send contents so far to the browser // iterate through all records, perform search for each 100 records (max per call) // and tabulate data for ($i = 1; $i <= ($submit->len); $i+=100) { // set search parameters for current iteration (first record = 1, 101, 201, 301 etc.) $submit->data['retrieveParameters']['firstRecord'] = $i; // gather search response for current iteration try { $submit->search_response = $submit->search_client->search($submit->data); } catch (Exception $e) { echo $e->getMessage(); }; // turn Soap Client object from current response into XML element $xml = simplexml_load_string($submit->search_response->return->records); // save variable names for citations, country and publication year $citations = ""; $pubyear = ""; $country = ""; // iterate through current data set and store to $records array foreach($xml->REC as $record) { // create authors array for this REC data $authors = []; echo "<script type='text/javascript'> setRecord(" .$counter. "); </script>"; ob_flush(); // flush anything from the header output buffer flush(); // send contents so far to the browser // authors foreach($record->static_data->summary->names->name as $thisAuthor) { array_push($authors, $thisAuthor->full_name); } // country (if exists) if (isset($record->static_data->item->reprint_contact->address_spec->country)) { $country = (string)$record->static_data->item->reprint_contact->address_spec->country; } else { $country = ""; }; // set current publication year $pubyear = (string)$record->static_data->summary->pub_info->attributes()->pubyear; // number of citations, if 0-3 ($ignore array) then 'break' out of loop entirely if (!in_array($record->dynamic_data->citation_related->tc_list->silo_tc->attributes(), $ignore)) { $citations = (string)$record->dynamic_data->citation_related->tc_list->silo_tc->attributes(); } else { // break from both loops break 2; }; // for this iteration map all the values recorded into a temporary array variable, // $aRecord (equivalent to one row of data in table) $arecord = [ "authors" => $authors, "ID" => "", "pubyear" => $pubyear, "country" => $country, "citations" => $citations ]; // pass the data from this iteration into the array variable '$records', // after all iterations, each element in $records will be a single // record or row of data for a single journal array_push($submit->records, $arecord) ; } // increment for next record $counter+=100; } } };
Поэтому, хотя он отображает этот первый бит HTML, #alertBox
, он не имеет стиля и не может вызвать setRecord()
поскольку модель может иметь ссылки CSS или JS. Как я должен это делать? С AJAX? Или мне нужно передать переданные данные другому представлению, чтобы отобразить экран загрузки во время обработки данных, а затем передать данные на конечную страницу результатов по завершении?
**** Дополнительная информация ****
Я попытался добавить ссылки на echo
d HTML, а также некоторые встроенные стили, но это, похоже, не работает:
// panel to display records loading progress, js updates current record in #progressPanel echo "<link href='//maxcdn.bootstrapcdn.com/bootswatch/3.3.0/readable/bootstrap.min.css' rel='stylesheet'> <script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script> <style> #alertBox {position:fixed !important;left: 35% !important;top: 35% !important;} .glyphicon-info-sign {margin-left: 15px !important;} </style> <div class='panel panel-primary' id='alertBox'> <div class='panel-heading'> <h1 class='panel-title'> PROGRESS<span class='glyphicon glyphicon-info-sign'></span> </h1> </div> <div class='panel-body'> <p id='progressPanel'></p> <p>The <strong>maximum</strong> estimated time for this query is " .$minutes. " minutes & " .$seconds. " seconds</p> <h2> <button type='submit' class='back btn btn-primary' onclick='window.location.href = '/';'> <span class='glyphicon glyphicon-remove'></span> <strong>Cancel</strong> </button> </h2> </div> </br> <div id='processing' hidden> <h4 class='text-primary'>Processing retrieved data...</h4> <div class='progress progress-striped active'> <div class='progress-bar' style='width: 100%''></div> </div> </div> </div>";