How does text url parameter work? [duplicate] - html

This question already has answers here:
Backbone router with multiple parameters
(2 answers)
Closed 6 years ago.
PLEASE INVEST SOME TIME READING THE QUESTION COMPLETELY BEFORE MARKING OR ANSWERING
I want to display text from data in url and access it using the same. Eg.
http://stackoverflow.com/questions/24888693/how-does-out-parameter-work
Notice how this page is accessed using the param how-does-out-parameter-work
Currently i am using requireJs with backboneJs in my web app. So, in my router i am routing like
siteTitle = 'Boiler Plate';
define([
'jquery',
'underscore',
'backbone',
'handlebars',
'jcookie',
'views/home',
'views/404'
], function ($, _, Backbone, Handlebars, jcookie, HomePage, FoFPage) {
var AppRouter = Backbone.Router.extend({
routes: {
':*':'home',
'home' : 'home',
'home/:a' : 'home',
'*whatever' : '404'
},
home: function (a) {
document.title = siteTitle + ' - Home';
homePage = new HomePage({route: a});
homePage.render();
},
404: function(){
document.title = siteTitle + ' - 404';
fofPage = new FoFPage;
fofPage.render();
}
});
var initialize = function () {
var app_router = new AppRouter;
Backbone.history.start();
};
return {
initialize: initialize,
AppRouter: AppRouter
}
});
Notice that i am getting the passed parameter a and them loading the page accordingly. Currently i am setting that parameter a as a number that is my post ID and using it accordingly. Bu if i want to pass a portion of my post's heading and access it how can i do that?
I can think of one way is selecting substring from mysql data base and based on url input but it wont help as if the parameter is how-does-out-parameter-work i can never parse it as How does 'out' (parameter) work? which is actual text in database. What am i missing?
UPDATE
the ignoring the post param is only applicable in stackvoerflow not on this site
https://www.theguardian.com/us-news/2016/nov/10/hate-crime-spike-us-donald-trump-president is using something else. What am i missing?

If you're attempting to follow the same process as Stackoverflow, they appear to use an Id for each question. I can only speculate what the title parameter is used for.
http://stackoverflow.com/questions/24888693/how-does-out-parameter-work
Equates to the following:
{domain}/{questions}/{questionId}/{title-string}
You can see that the title-string is an option parameter as the following will still route you to the correct question
http://stackoverflow.com/questions/24888693
The additional parameter is likely to stop duplicate Ids causing an issue in the database if the question Id counter has to be reset.
Maybe you can clarify why you need to search for a hypenated string in the databse?

Related

vue.js json object array as data

aye folks!
I'm currently learning to do stuff with vue.js. unfortunately i'm stuck atm. what i want to do is sending a request to my sample API which responds with a simple json formatted object.
I want to have this object as data in my component – but it doesn't seem to do that for whatever reason.
Ofc i tried to find a solution on stackoverflow but maybe i'm just blind or this is just like the code other people wrote. i even found this example on the official vue website but they're doing the same thing as i do .. i guess?
btw. When i run the fetchData() function in a separate file it does work and i can access the data i got from my API. no changes in the code .. just no vue around it. i'm really confused right now because i don't know what the mistake is.
code:
var $persons = [];
and inside my component:
data: {
persons: $persons,
currentPerson: '',
modal: false
},
created: function() {
this.fetchData()
},
methods: {
fetchData: function () {
var ajax = new XMLHttpRequest()
ajax.open('GET', 'http://api.unseen.ninja/data/index.php')
ajax.onload = function() {
$persons = JSON.parse(ajax.responseText)
console.log($persons[0].fname)
}
ajax.send()
}
},
[...]
link to the complete code
First, make sure that the onload callback is actually firing. If the GET request causes an error, onload won't fire. (In your case, the error is CORS-related, see this post suggested by #Pradeepb).
Second, you need to reference the persons data property directly, not the $persons array that you initialized persons with.
It would look like this (inside your fetchData method):
var self = this;
ajax.onload = function() {
self.persons = JSON.parse(ajax.responseText)
console.log($persons[0].fname)
}

How to access an html content json object via URL [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
So for example, if my URL is www.someurlsomewhere.com/GetItemById?Id=5 and my response is an array of json objects.
Success: true
Html: "<html><body>test</body></html>"
FileName: "test.html"
How do I say www.someurlsomewhere.com/GetItemById?Id=5?data=Html to make it act like a link to the Html part of my json object within response.
You are talking about Query Parameters or URL Parameters. The correct format for adding multiple parameters is separating them with &. Your URL would look similar to: www.someurlsomewhere.com/GetItemByID?Id=5&src=html.
To extract that information, you would need to parse the URL parameters and then serve up the information that you want based on the data. This can be done server side or client side. Look up URL Parameter Parsing to get ideas on how to do it in the language of your choice. One of the examples that comes up in JavaScript is How can I get query string values in JavaScript?.
After you've parsed the URL parameter out that you want, now you need to render it to the page. Look up Parsing HTML. I'm going to assume you're doing it in javascript, just to give you an example of parsing:
var data = {
success: true,
html: "<html><body>test</body></html>",
filename: "test.html"
}
var el = document.createElement('html'); //creates a temporary dummy element to append to the page... although if you already have something on the page, you may use that container
el.innerHTML = data.html; //here you're selecting the element and adding a string of HTML to it
There are a lot of unknowns about what you're asking. But here is a potential client side solution that retrieves the URL parameter then passes it as HTML to the DOM.
<script>
//Assuming your URL looks like this:
// www.someurlsomewhere.com/GetItemByID?Id=5&src=html
function getParameterByName(name, url) {
if (!url) {
url = window.location.href;
}
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var src = getParameterByName('src'); //Use your parameter function to retrieve the src parameter from the URL. Currently src = 'html'
//This is a representation of your JSON payload that you're receiving from somewhere
var data = {
success: true,
html: "<html><body>test</body></html>",
filename: "test.html"
}
var el = document.createElement('html'); //creates a temporary dummy element to append to the page... although if you already have something on the page, you may use that container
el.innerHTML = data[src]; //here you're selecting the element and adding a string of HTML to it. This would translate to data.html
</script>

How to use Dynamic URL's to create Dynamic pages in Angular JS

I have put the question at the bottom as the only way I could explain my problem was with an example so with out the example it might not make sense but feel free to skip down to the bottom and just read the question.
I will use this example to try give some idea of what I do understand and where my understanding falls down.
I want to build a page where I can browse through a collection of items which I would set up like this:
angular.module('App')
.config(['$stateProvider', function ($stateProvider) {
$stateProvider
.state('browse', {
url: '/browse',
templateUrl: 'app/browse/browse.html',
controller: 'BrowseCtrl',
title: 'Browse',
mainClass: 'browse'
});
}]);
Each item is pulled through and place on this page using ng-repeat and then calling an api:
$scope.items = [];
$http.get('/api/items').success(function(items) {
$scope.items = items;
socket.syncUpdates('Item', $scope.items);
$scope.totalItems = $scope.items.length;
$scope.$watch('currentPage + itemsPerPage', function() {
var begin = (($scope.currentPage - 1) * $scope.itemsPerPage),
end = begin + $scope.itemsPerPage;
$scope.filteredItems = $scope.items.slice(begin, end);
});
});
This then accesses the api and repeats out the items. So far so good. Heres an example of the API setup. Worth mentioning I am using the Angular-fullstack generator which plugs in to Mongo DB using Express & Sockets.io
Item.find({}).remove(function() {
Item.create({
"image_url" : "../../../assets/images/test.jpg",
"title" : "Test Item",
"created_on" : new Date(2014, 9, 23, 3, 24, 56, 2),
"creator" : {
"profile_img" : "../../../assets/images/stephanie-walters.jpg",
"username" : "StephW",
"url" : "/stephanie-walters",
"first_name" : "Stephanie",
"last_name" : "Walters",
}
}
Ok now this is where things start to get unclear for me.
I now need to create the item pages, so that when I click on an item I get access to the content of that item. Short of creating every single page for every entry I would very much like to be able to create a page template that ui-router is able to attach content to when the correct url structure is met.
Thats probably not clear so let me try be a bit clearer. Lets say if we follow that JSON above I want to go to 'Stephanie Walters' profile I am going to need three things.Firstly a profile template, secondly I need the content for the profile in an api call and lastly a dynamic url that can take that api content and put it in to the page template.
Perhaps something similar to:
.state('profile.username', {
url: '/:username',
templateUrl: '/partials/profile.username.html',
controller: 'profileUsernameCtrl'
})
But I don't exactly understand how to get the take a variable like username from the item JSON(above) and then use that to build a URL /:username that connects to a template page profile.username.html and further still fill that page with the users content that is stored in another API call.
To "build a url" so to speak, you need to use the ui-sref directive.
Given a state like so:
.state('profile.username', {
url: '/:username',
templateUrl: '/partials/profile.username.html',
controller: 'profileUsernameCtrl'
})
to create a link to this state use:
<a ui-sref="profile.username({username: user.name})">{{ user.name }}</a>
where user is an attribute on the scope where that link is displayed.
For more complex URLs you just add additional parameters like so:
.state('browse.item', {
url: '/:username/:itemId'
})
To get the parameters you use the $stateParams service in your controller like so:
.controller('MyController', function($scope, $stateParams) {
$scope.username = $stateParams.username;
$scope.itemId = $stateParams.itemId;
})

Using controller-scoped data in a directive's jqlite-generated html

This question is similiar to them one asked in Mike's post Using ng-model within a directive.
I am writing a page which is small spreadsheet that displays calculated output based on user input fields. Using a directive, I'm making custom tags like this:
<wbcalc item="var1" title="Variable 1" type="input"></wbcalc>
<wbcalc item="var2" title="Variable 2" type="input"></wbcalc>
<wbcalc item="calc" title="Calculation" type="calc"></wbcalc>
The 'item' field references scoped data in my controller:
$scope.var1 = '5'; // pre-entered input
$scope.var2 = '10'; // pre-entered input
$scope.calc = function() {
return parseInt($scope.var1) + parseInt($scope.var2);
};
And the 'type' field is used in the directive's logic to know whether to treat the item as a string or a function.
Here's a fiddle for this: http://jsfiddle.net/gregsandell/PTkms/3/ I can get the output elements to work with the astonishing line of code:
html.append(angular.element("<span>")
.html(scope.$eval(attrs.item + "()"))
);
...and I'm using this to get my inputs connected to my scoped controller data (I got this from Mike's post:
var input = angular.element("<input>").attr("ng-model", attrs.item);
$compile(input)(scope);
html.append(input);
...while it does put the values in the fields, they aren't bound to the calculation, as you can see by changing inputs in my fiddle.
Is there a better and/or more intuitive way to link my controller-scoped data to the jqlite-generated html in my directive?
Take a look at this, I think you can simplify the process a fair bit.
http://jsfiddle.net/PTkms/4/
angular.module('calculator', []).directive('wbcalc', function($compile) {
return {
restrict: 'E',
template: '<div><div class="span2">{{title}}</div><input ng-model="item"></div>',
scope: {
title: '#',
item: '='
},
link: function(scope, element, attrs) {
// Don't need to do this.
}
}
});
function calcCtrl($scope) {
$scope.var1 = '5';
$scope.var2 = '10';
$scope.calc = function() {
// Yes, this is a very simple calculation which could
// have been handled in the html with {{0 + var1 + var2}}.
// But in the real app the calculations will be more
// complicated formulae that don't belong in the html.
return parseInt($scope.var1) + parseInt($scope.var2);
};
}
I know you said you like jQuery - but to make best use of Angular you need to think in an Angular way - use bindings, don't manipulate the DOM directly etc.
For this example, it would be helpful to read up on the isolated scope bindings used - '#' and '=', see:
http://docs.angularjs.org/guide/directive

using multiple json request with backbone.js

I have recently started working with backbone.js and i am finally started to get my head around after many tutorials.
One thing i am stuck on is how to use the routing to allow a list to pull different rest request.
Say i have the following in my collection
var NewsCollection = Backbone.Collection.extend({
model : News,
url: 'http://api.example.com/index.php/news/all/format/json',
});
From my understanding correct me if i am wrong backbone stores all the data pulled from the above feed into my model that extends this collection, this will all work i will pull in the feed and then display it in the view
This is where i get confused within my routing i have the following.
var NewsRouter = Backbone.Router.extend({
routes: {
"": "defaultRoute",
"news/:country_code":"updatedRoute"
},
defaultRoute: function () {
console.log("defaultRoute");
var movies = new NewsCollection()
new NewsView({ collection: movies });
movies.fetch();
//setInterval(function(){movies.fetch({success: function(){}});}, 60000);
},
updatedRoute:function (country_code) {
//confused
this.movie = this.movies.get(country_code);
}
})
I need to run the updatedRoute function when that will display a list of news based on cat of country code see below.
http://api.example.com/index.php/news/country/gb/format/json
How do i update the whole feed when a list item is click so the browser url would be.
http://localhost:8888/backbonetut/#news/gb
my list item is.
<li><a href='#news/gb'>GB</a></li>
I can get that in the updateRoute function with
this.movie = this.movies.get(country_code);
Can someone please help
You can either override the fetch function on your collection or temporarily change the url of the collection in your router action.